****************************
* Set all globals 
****************************
*ssc install erepost 

* Summary statistics 
global vars age_firstinphospital male ///
gestation_weeks birth_weight ///
mother_age age_mother_inp finnish single married ///
educ1 educ2 educ3 educ4 educ5 educ6 ///
highskilled_whitecollar lowskilled_whitecollar manualworkers ///
selfemployed income_yearminus2 working2 unemp_yearminus2 ///
totalincome_yearminus2 mentalhealthyearminus2_any public_yearminus2 ///
changejob_yearminus2 divorced_yearminus2 age_father_inp father_educ1 father_educ2 ///
father_educ3 father_educ4 father_educ5 father_educ6 father_income_yearminus2 ///
f_working2 father_unemp_yearminus2 f_totalincome_yearminus2 ///
mentalhealthdadyearminus2_any father_public_yearminus2 father_changejob_yearminus2


* Sample Restrictions
** Child age during health shock and year in hospital
global year_did inrange(yearinp,1995,2014) 
global year_mh inrange(yearinp,1995,2013) 
global year_is inrange(yearinp,2000,2014)

** Overall DiD Controls and Outcomes 
*** Full set of controls for hospitaizations
global outcomecontrols !missing(father_income) & !missing(income) & ///
!missing(treat) & !missing(age_mother) & ///
!missing(age_father) & !missing(year_calendar) & ///
!missing(child_b_year) & !missing(educ0) & ///
!missing(father_educ0) & !missing(male)

*** Full set of controls with the exclusion of education for mortality
global outcomecontrols2 !missing(father_income) & !missing(income) & ///
!missing(treat) & !missing(age_mother) & ///
!missing(age_father) & !missing(year_calendar) & ///
!missing(child_b_year) & !missing(male)

** Overall DiD Sample
*** Hospitalizations
global sample_did $year_did & $outcomecontrols
*** Mortality
global sample_did_mortality $year_did & $outcomecontrols2

** Mental health
*** Hospitalizations
global sample_mh $year_mh & $outcomecontrols & ///
!missing(mentalhealth) & !missing(dadmentalhealth)
*** Mortality
global sample_mh_mortality $year_mh & $outcomecontrols2 & ///
!missing(mentalhealth) & !missing(dadmentalhealth)

** Institutional Support 
*** Hospitalizations
global sample_is $year_is & $outcomecontrols & /// 
!missing(totalincome) & !missing(transfers) & !missing(fam_allow) & ///
!missing(f_totalincome) & !missing(father_transfers) & !missing(f_fam_allow)
*** Mortality
global sample_is_mortality $year_is & $outcomecontrols2 & /// 
!missing(totalincome) & !missing(transfers) & !missing(fam_allow) & ///
!missing(f_totalincome) & !missing(father_transfers) & !missing(f_fam_allow)

** Event study restrictions
global sample_event !missing(father_income) & !missing(income) ///
& !missing(year_calendar) & inrange(age_firstinphospital,7,18) & inrange(yearinp,1995,2014) 

global sample_event_mortality !missing(father_income) & !missing(income) ///
& !missing(year_calendar) & inrange(age_firstmortality,7,18) & inrange(yearinp,1995,2014) 

*exit 



**********************************************************
* Figure 1: Differences in Characteristis: Within Affected Families 
**********************************************************
{
    
* Matched Sample Data DiD Hospitalizations *

use "$processed_data\date_diagnosis.dta", clear 

* Implement sample conditions
keep if sample_hospital == 1

* Clean date_diagnosis
** Not Finnish
g nonfinnish =(finnish == 0)
replace nonfinnish = . if finnish == .
label var nonfinnish "Non-finnish"
** Single 
label var single "Single"
** Married
label var married "Married"

* merge mothers income
merge 1:m shnro_mother using "$processed_data\mothers_income_diagnosis4", keep(3) nogen

local variables male gestation_weeks birth_weight ///
mother_age finnish nonfinnish single married  ///
educ1 educ2 educ3 educ4 educ5 educ6 ///
highskilled_whitecollar lowskilled_whitecollar manualworkers ///
selfemployed ///

eststo clear
foreach var of local variables {
	egen `var'_z = std(`var')
	local label : variable label `var'
	label variable `var'_z `"`label'"'
}

foreach var of local variables {
	eststo `var':  reg `var'_z treat i.child_b_year, cluster(shnro_mother)
}
set scheme plotplain
coefplot male, bylabel("Male") ///
|| mother_age, bylabel("Mother age")  ///
|| nonfinnish, bylabel("Non-finnish") ///
|| single, bylabel("Single") ///
|| married, bylabel("Married") ///
|| educ1, bylabel("Secondary") ///
|| educ2, bylabel("Post-secondary") ///
|| educ3, bylabel("Short-cycle tertiary") ///
|| educ4, bylabel("Bachelor's") ///
|| educ5, bylabel("Master's") ///
|| educ6, bylabel("Doctoral") ///
|| highskilled_whitecollar,  bylabel("High-skilled") ///
|| lowskilled_whitecollar, bylabel("Low-skilled") ///
|| manualworkers, bylabel("Manual workers") ///
|| selfemployed, bylabel("Self-employed") ///
keep(treat)  xtitle("Delta = 4") ///
xlabel(-0.15(0.10)0.15,nogrid) ylabel(,nogrid) ytitle("") ///
graphregion(color(white)) bgcolor(white) bycoefs xline(0, lcolor(black)) ///
ciopts(recast(rcap) color(black*0.5)) levels(95) aspectratio(1) ///
coeflabels(,labsize (small)) mcolor(black) msize(vsmall) msymbol(circle_hollow)
 
 
graph export "$output/figure 1_fi.pdf",as(pdf) replace

}

**********************************************************
* Figure 2: Hospitalizations: Mothers' and Fathers' Labor Earnings
**********************************************************
{

use "$processed_data\date_diagnosis.dta", clear 

merge 1:m shnro_mother using "$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using "$processed_data\fathers_income_diagnosis4", keep(3) nogen 

keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp income_* ///
father_income_* educ0 child_b_year father_educ0 male treat ageinptreat year_treat

egen new_shnromother = group(shnro_mother treat)
reshape long income_ father_income_, ///
i(new_shnromother) j(year_event) string
drop new_shnromother
rename income_ income
rename father_income_ father_income
 
* gen numeric variable for time w.r.t to the hospitalization
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Figure 3
** Set controls
global controls i.treat i.age_mother i.age_father ///
i.year_calendar i.child_b_year i.educ0 i.father_educ0 male


** Implement conditions
keep if $sample_did

** Figure: labor earnings mother, ylabel (%)
*** Regress 
estimates clear
*** Gen mother's Income as percentage of time at -2
egen mean_minus1_ = mean(income) if time_event == -2
replace mean_minus1_ = 0 if mean_minus1_ == .
egen mean_minus1 = max(mean_minus1_)
gen income_pct = (income/mean_minus1)*100
reg income_pct $event_dummies $event_treat_dummies $controls, cluster(shnro_mother)
estimates store incomemom

preserve
*** coefficients of time to event
gen coef_event_time_pctg=.
g boundL_pctg =.
g boundH_pctg=.
foreach x of numlist 1/3 5/9{
replace coef_event_time_pctg=_b[even`x'_treat] if time_event==(`x'-6)
replace boundL_pctg = _b[even`x'_treat] -1.96*_se[even`x'_treat] if time_event==(`x'-6)
replace boundH_pctg = _b[even`x'_treat] + 1.96*_se[even`x'_treat] if time_event==(`x'-6)
}
replace coef_event_time_pctg=0 if time_event==-2 // omitted category, -2

collapse  coef_event_time_pctg boundH_pctg boundL_pctg ,by(time_event)

** Confidence intervals as vertical lines
twoway (rspike boundL_pctg boundH_pctg time_event, ///
color(gs8*0.5) lcolor(gs8*0.5) pstyle(p1)) ///
(scatter coef_event_time_pctg time_event, msymbol(circle) ///
mcolor(gs8) lcolor(gs8)), ytitle("Earnings (%)", size(medsmall)) ///
xtitle("Event time (years)") xline(-0.5,lcolor(black)) xlabel(-5(1)3,nogrid) ///
yline(0, lpattern(dash) lcolor(black)) ylabel(4(2)-8,nogrid) ///
graphregion(color(white)) legend(off) bgcolor(white)

graph export "$output/figure 2mom_fi.pdf",as(pdf) replace
restore 


** Figure: labor earnings father, ylabel (%)
*** Father's Income as percentage of time at -2
egen mean_minus1f_ = mean(father_income) if time_event == -2
replace mean_minus1f_ = 0 if mean_minus1f_ == .
egen mean_minus1f = max(mean_minus1f_)

gen father_income_pct = (father_income/mean_minus1f)*100
reg father_income_pct $event_dummies $event_treat_dummies $controls, vce(cluster  shnro_father)
estimates store incomedad

** coefficients of time to event
gen coef_event_time_pctg_f=.
g boundL_pctg_f =.
g boundH_pctg_f=.
foreach x of numlist 1/3 5/9{
replace coef_event_time_pctg_f=_b[even`x'_treat] if time_event==(`x'-6)
replace boundL_pctg_f = _b[even`x'_treat] -1.96*_se[even`x'_treat] if time_event==(`x'-6)
replace boundH_pctg_f = _b[even`x'_treat] + 1.96*_se[even`x'_treat] if time_event==(`x'-6)
}
replace coef_event_time_pctg_f=0 if time_event==-2 // omitted category, -2

preserve
collapse  coef_event_time_pctg_f boundH_pctg_f boundL_pctg_f ,by(time_event)

twoway (rspike boundL_pctg_f boundH_pctg_f time_event, color(gs5*0.5) ///
lcolor(gs5*0.5) pstyle(p1)) ///
(scatter coef_event_time_pctg_f time_event, msymbol(circle) ///
mcolor(gs5) lcolor(gs5)), ytitle("Earnings (%)", size(medsmall)) ///
xtitle("Event time (years)") xline(-0.5,lcolor(black)) ///
xlabel(-5(1)3,nogrid)  yline(0, lpattern(dash) lcolor(black)) ///
ylabel(4(2)-8,nogrid) graphregion(color(white)) legend(off) bgcolor(white)

graph export "$output/figure 2dad_fi.pdf",as(pdf) replace
restore

}

**********************************************************
* Figure 3: Impact of a Child's Fatal Shock on Mothers' and Fathers' Labor Earnings
**********************************************************
{

* All mortality 
use "$processed_data\date_mortality.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4_mortality", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4_mortality", keep(3) nogen 
 
* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp income_* ///
father_income_* educ0 child_b_year father_educ0 male treat ageinptreat year_treat

egen new_shnromother = group(shnro_mother treat)
reshape long income_ father_income_ ,i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income

* gen numeric variable for time w.r.t to the hospitalization
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Figure 3
set scheme plotplainblind
** Set controls
global controls_mother i.treat i.age_mother i.year_calendar ///
i.child_b_year male
global controls_father i.treat i.age_father i.year_calendar ///
i.child_b_year male

** Implement conditions
keep if $sample_did_mortality

** Figure: labor earnings mother, ylabel (%)
*** Regress 
estimates clear
*** Gen mother's Income as percentage of time at -2
egen mean_minus1_ = mean(income) if time_event == -2
replace mean_minus1_ = 0 if mean_minus1_ == .
egen mean_minus1 = max(mean_minus1_)
gen income_pct = (income/mean_minus1)*100
reg income_pct $event_dummies $event_treat_dummies $controls_mother, cluster(shnro_mother)
estimates store incomemom

preserve
*** coefficients of time to event
gen coef_event_time_pctg=.
g boundL_pctg =.
g boundH_pctg=.
foreach x of numlist 1/3 5/9{
replace coef_event_time_pctg=_b[even`x'_treat] if time_event==(`x'-6)
replace boundL_pctg = _b[even`x'_treat] -1.96*_se[even`x'_treat] if time_event==(`x'-6)
replace boundH_pctg = _b[even`x'_treat] + 1.96*_se[even`x'_treat] if time_event==(`x'-6)
}
replace coef_event_time_pctg=0 if time_event==-2 // omitted category, -2

collapse  coef_event_time_pctg boundH_pctg boundL_pctg ,by(time_event)

twoway (rspike boundL_pctg boundH_pctg time_event, color(gs8*0.5) lcolor(gs8*0.5) pstyle(p1)) ///
(scatter coef_event_time_pctg time_event, msymbol(circle) mcolor(gs8) lcolor(gs8)), ///
ytitle("Earnings (%)", size(medsmall)) xtitle("Event time (years)") ///
xline(-0.5,lcolor(black)) xlabel(-5(1)3,nogrid)  ///
yline(0, lpattern(dash) lcolor(black)) ylabel(12(4)-32,nogrid) ///
graphregion(color(white)) legend(off) bgcolor(white)

graph export "$output/figure 3a mom_fi.pdf",as(pdf) replace

restore

** Figure: labor earnings father, ylabel (%)
*** Father's Income as percentage of time at -2
egen mean_minus1f_ = mean(father_income) if time_event == -2
replace mean_minus1f_ = 0 if mean_minus1f_ == .
egen mean_minus1f = max(mean_minus1f_)
gen father_income_pct = (father_income/mean_minus1f)*100
reg father_income_pct $event_dummies $event_treat_dummies $controls_father, vce(cluster  shnro_father)
estimates store incomedad

** coefficients of time to event
gen coef_event_time_pctg_f=.
g boundL_pctg_f =.
g boundH_pctg_f=.
foreach x of numlist 1/3 5/9{
replace coef_event_time_pctg_f=_b[even`x'_treat] if time_event==(`x'-6)
replace boundL_pctg_f = _b[even`x'_treat] -1.96*_se[even`x'_treat] if time_event==(`x'-6)
replace boundH_pctg_f = _b[even`x'_treat] + 1.96*_se[even`x'_treat] if time_event==(`x'-6)
}
replace coef_event_time_pctg_f=0 if time_event==-2 // omitted category, -2

preserve
collapse  coef_event_time_pctg_f boundH_pctg_f boundL_pctg_f ,by(time_event)

twoway (rspike boundL_pctg_f boundH_pctg_f time_event, color(gs5*0.5) ///
lcolor(gs5*0.5) pstyle(p1)) (scatter coef_event_time_pctg_f time_event, ///
msymbol(circle) mcolor(gs5) lcolor(gs5)), ///
ytitle("Earnings (%)", size(medsmall)) ///
xtitle("Event time (years)") ///
xline(-0.5,lcolor(black)) xlabel(-5(1)3,nogrid) ///
yline(0, lpattern(dash) lcolor(black)) ylabel(12(4)-20,nogrid) ///
graphregion(color(white)) legend(off) bgcolor(white)

graph export "$output/figure 3a dad_fi.pdf",as(pdf) replace
restore


* Accidental (injury) mortality 
use "$processed_data\date_mortality.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4_mortality_acc", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4_mortality_acc", keep(3) nogen 
 
* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp income_* ///
father_income_* educ0 child_b_year father_educ0 male treat ageinptreat year_treat

egen new_shnromother = group(shnro_mother treat)
reshape long income_ father_income_ ,i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income

* gen numeric variable for time w.r.t  hospitalization
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Figure 3
set scheme plotplainblind
** Set controls
global controls_mother i.treat i.age_mother i.year_calendar ///
i.child_b_year male
global controls_father i.treat i.age_father i.year_calendar ///
i.child_b_year male

** Implement conditions
keep if $sample_did_mortality

** Figure: labor earnings mother, ylabel (%)
*** Regress 
estimates clear
*** Gen mother's Income as percentage of time at -2
egen mean_minus1_ = mean(income) if time_event == -2
replace mean_minus1_ = 0 if mean_minus1_ == .
egen mean_minus1 = max(mean_minus1_)
gen income_pct = (income/mean_minus1)*100
reg income_pct $event_dummies $event_treat_dummies $controls_mother, cluster(shnro_mother)
estimates store incomemom

preserve
*** coefficients of time to event
gen coef_event_time_pctg=.
g boundL_pctg =.
g boundH_pctg=.
foreach x of numlist 1/3 5/9{
replace coef_event_time_pctg=_b[even`x'_treat] if time_event==(`x'-6)
replace boundL_pctg = _b[even`x'_treat] -1.96*_se[even`x'_treat] if time_event==(`x'-6)
replace boundH_pctg = _b[even`x'_treat] + 1.96*_se[even`x'_treat] if time_event==(`x'-6)
}
replace coef_event_time_pctg=0 if time_event==-2 // omitted category, -2

collapse  coef_event_time_pctg boundH_pctg boundL_pctg ,by(time_event)

twoway (rspike boundL_pctg boundH_pctg time_event, color(gs8*0.5) lcolor(gs8*0.5) pstyle(p1)) ///
(scatter coef_event_time_pctg time_event, msymbol(circle) mcolor(gs8) lcolor(gs8)), ///
ytitle("Earnings (%)", size(medsmall)) xtitle("Event time (years)") ///
xline(-0.5,lcolor(black)) xlabel(-5(1)3,nogrid)  ///
yline(0, lpattern(dash) lcolor(black)) ylabel(12(4)-32,nogrid) ///
graphregion(color(white)) legend(off) bgcolor(white)

graph export "$output/figure 3b mom_fi.pdf",as(pdf) replace

restore

** Figure: labor earnings father, ylabel (%)
*** Father's Income as percentage of time at -2
egen mean_minus1f_ = mean(father_income) if time_event == -2
replace mean_minus1f_ = 0 if mean_minus1f_ == .
egen mean_minus1f = max(mean_minus1f_)
gen father_income_pct = (father_income/mean_minus1f)*100
reg father_income_pct $event_dummies $event_treat_dummies $controls_father, vce(cluster  shnro_father)
estimates store incomedad

** coefficients of time to event
gen coef_event_time_pctg_f=.
g boundL_pctg_f =.
g boundH_pctg_f=.
foreach x of numlist 1/3 5/9{
replace coef_event_time_pctg_f=_b[even`x'_treat] if time_event==(`x'-6)
replace boundL_pctg_f = _b[even`x'_treat] -1.96*_se[even`x'_treat] if time_event==(`x'-6)
replace boundH_pctg_f = _b[even`x'_treat] + 1.96*_se[even`x'_treat] if time_event==(`x'-6)
}
replace coef_event_time_pctg_f=0 if time_event==-2 // omitted category, -2

preserve
collapse  coef_event_time_pctg_f boundH_pctg_f boundL_pctg_f ,by(time_event)

twoway (rspike boundL_pctg_f boundH_pctg_f time_event, color(gs5*0.5) ///
lcolor(gs5*0.5) pstyle(p1)) (scatter coef_event_time_pctg_f time_event, ///
msymbol(circle) mcolor(gs5) lcolor(gs5)), ///
ytitle("Earnings (%)", size(medsmall)) ///
xtitle("Event time (years)") ///
xline(-0.5,lcolor(black)) xlabel(-5(1)3,nogrid) ///
yline(0, lpattern(dash) lcolor(black)) ylabel(12(4)-20,nogrid) ///
graphregion(color(white)) legend(off) bgcolor(white)

graph export "$output/figure 3b dad_fi.pdf",as(pdf) replace
restore

}



**********************************************************
* Table 1: Hospitalizations: Mothers' Institutional Support
**********************************************************
{
use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 ///
transfers_* father_transfers* totalincome_* f_totalincome_* ///
income_* father_income_* fam_allow_* f_fam_allow_*

egen new_shnromother = group(shnro_mother treat)
reshape long transfers_ father_transfers_ totalincome_ ///
f_totalincome_ income_ father_income_ fam_allow_ f_fam_allow_, ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename transfers_ transfers
rename father_transfers_ father_transfers
rename totalincome_ totalincome
rename f_totalincome_ f_totalincome
rename fam_allow_ fam_allow
rename f_fam_allow_ f_fam_allow
 
* gen numeric variable for time w.r.t hospitalization
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_5 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table 3
** Set controls
global controls i.treat i.age_mother i.age_father i.year_calendar ///
i.child_b_year i.educ0 i.father_educ0 male

** Implement conditions
keep if $sample_is
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat


** Income (euro)
reg income post treat post_treat $controls, cluster(shnro_mother) coeflegend
estimates store incomemom
estadd local controls "YES"
sum income if time_event == -2 
estadd scalar ymean = r(mean)

** Total income (euro)
reg totalincome post treat post_treat $controls, cluster(shnro_mother) coeflegend
estimates store totalincomemom
estadd local controls "YES"
sum totalincome if time_event == -2 
estadd scalar ymean = r(mean)

** Transfers (euro)
reg transfers  post treat post_treat $controls, cluster(shnro_mother) coeflegend
estimates store transfersmom
estadd local controls "YES"
sum transfers if time_event == -2 
estadd scalar ymean = r(mean)

** Allowance (euro)
reg fam_allow  post treat post_treat $controls, cluster(shnro_mother) coeflegend
estimates store allowmom
estadd local controls "YES"
sum fam_allow if time_event == -2 
estadd scalar ymean = r(mean)

* Output Mothers 
esttab incomemom totalincomemom transfersmom allowmom ///
using "$output\table 1_fi.tex", label replace ///
addnotes("This table shows the impact of a child's hospitalization on maternal income (in column (1)) total income (in column (2)), transfers received by the mother (in column (3)), and family allowance (in column (4)), for both Finland and Norway, respectively. The table shows the coefficient for the interaction between a post dummy (after hospitalization) and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Income (\euro)" "Total Income (\euro)" "Transfers (\euro)" ///
"Family Allowance (\euro)") ///
keep(post_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) 

}

**********************************************************
* Table 2: Hospitalizations: Heterogeneity Analysis (Burden of care and severity)
**********************************************************
{
    
* High and low burden (DiD), cancer vs skin (DID), same vs different region grandparents (DID)
estimates clear
foreach name in "4_h_mean" "4_l_mean" "4_cancer" "4_skin" "_region0" "_region1" {
	
	use "$processed_data\date_diagnosis.dta", clear 
	merge 1:m shnro_mother using ///
	"$processed_data\mothers_income_diagnosis`name'", keep(3) nogen 
	merge 1:1 shnro_mother treat using ///
	"$processed_data\fathers_income_diagnosis`name'", keep(3) nogen 

	* Put in long format
	keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
	child_b_year male treat ageinptreat year_treat educ0 father_educ0 ///
	income_* father_income_*

	egen new_shnromother = group(shnro_mother treat)
	reshape long income_ father_income_, i(new_shnromother) j(year_event) string
	rename income_ income
	rename father_income_ father_income
	 
	* gen numeric variable for time w.r.t hospitalization
	gen time_event=.
	forvalues x=0(1)3{
		replace time_event=`x' if year_event=="year`x'"
	}
	forvalues x=1(1)5{
		replace time_event=-`x' if year_event=="yearminus`x'"
	}

	* gen year of income (calendar year)
	gen year_calendar=year_treat + time_event

	* gen age of mother in each year
	gen mother_b_year=year_treat - age_mother_inp
	gen age_mother=year_calendar - mother_b_year

	* gen age of father in each year
	gen father_b_year=year_treat - age_father_inp
	gen age_father=year_calendar - father_b_year

	* dummify time_event, with -2 as omitted variable
	** all but i_time_even_4 (-2 time_event)
	xi i.time_event,prefix("i_") noomit
	global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
	i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

	* g interactions 
	local time_to_shock = -5 
	forvalues i= 1(1)9{
		g even`i'_treat = i_time_even_`i'*treat
		label var even`i'_treat "`time_to_shock'"
		local ++time_to_shock 
	}

	** all but i_time_even_4 (-2 time_event)
	global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
	even6_treat even7_treat even8_treat even9_treat

	forvalues i= 1(1)3{
		local x = `i' + 6 
		label var i_time_even_`x' "`i' years after hospitalization" 
	}
	forvalues i= 1(1)5 {
		local x =  6 - `i'
		label var i_time_even_`i' "`x' years before hospitalization"
	}

	label var i_time_even_6 "Year of hospitalization" 

	* Table 2
	** Set controls
	global controls i.treat i.age_mother i.age_father ///
	i.year_calendar i.child_b_year i.educ0 i.father_educ0 male
	
	** Implement conditions
	keep if $sample_did
	g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat

	** Earnings (Euro)
	reg income post treat post_treat $controls, cluster(shnro_mother)
	estimates store inc_`name'
	estadd local controls "YES"
	sum income if time_event == -2
	estadd scalar ymean = r(mean)
	
} 






** Output
esttab inc_4_h_mean inc_4_l_mean inc_4_cancer inc_4_skin inc__region0 inc__region1 ///
using "$output\table 2_fi.tex", label replace ///
addnotes("This table shows the impact of children's hospital admission on maternal earnings (Euro) for different subsamples of hospitalizations. In column (1), we split the sample by burden of care, measured by the number of visits and hospitalizations after the main shock. In column (2) we analyze cancer and skin conditions. In column (3), we split the sample by whether the grandparents live close to the family or not. The table shows the estimated coefficients for the interaction between the post and the treat dummy. We use administrative data from Finland. All specifications include controls for calendar year, child's year of birth, child's gender, and each parent's age and educational level. Standard erros are clustered at the parent level.'") ///
mtitles("High" "Low" "Cancer" "Skin" "Different" "Same") ///
keep(post_treat) ///
scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)

}




**********************************************************
* Figure A1: Descriptive: maternal socioeconomic background and children's health shocks
**********************************************************
* Figs a and c: hospitalization
{
    
* Import birth data
use "$processed_data\clean_births.dta", clear
bys lapsi_shnro child_b_year : gen dup = cond(_N== 1,0,_n)
drop if dup != 0
drop dup
ren aiti_shnro shnro_mother

* Merge overall data on births with datasets containing date of admission and dummy for hospitalization
** tupva: date of admission -- in 4.define_hospitalizations we keep the only 
** hospitalization for each child
local year_range 8793 9402 0310 2011 2012 2013 1417
** 87-93, 94-02, 03-10, 2011, 2012, 2013, 2014-2017
foreach range of local year_range {
    merge 1:1 lapsi_shnro using ///
		"$processed_data\d_inphospital`range'child.dta", update
		drop if _merge == 2
		drop _merge
}
** Change missings to 0
replace inphospital=0 if inphospital==.

* Sample Event Study Hospitalizations
merge m:1 shnro_mother using "$processed_data\date_diagnosis.dta", nogen 

* Generate age of first diagnosis
tab tupva_inphospital,m 
su age_firstinphospital
cap drop age_firstinphospital
gen age_firstinphospital=tupva_inphospital-child_b_date
replace age_firstinphospital=age_firstinphospital/365 // in years
su age_firstinphospital

* Clean date_diagnosis
** Not Finnish
g nonfinnish =(finnish == 0)
replace nonfinnish = . if finnish == .
label var nonfinnish "Non-finnish"
** Single 
label var single "Single"
** Married
label var married "Married"

* merge mothers income
merge m:1 shnro_mother using ///
"$processed_data\mothers_income_diagnosis_all", keepusing(educ*) keep(1 3) nogen 

* Implement conditions
drop if age_firstinphospital > 18 & age_firstinphospital < .
** Check
tab inphospital,m 
count if inphospital == 0 & !missing(age_firstinphospital)


g totalbirth = _N
g low_edu = 1 if educ0 == 3 | educ0== 4 | educ0 == 5 
replace low_edu = 0 if educ0 != . & low_edu != 1
	

	preserve
	
	bysort low_edu: egen totalhospitalizations = total(age_firstinphospital !=.)
	g pcthosp= (totalhospitalizations/totalbirth)*100

	su pct*
	collapse pcthosp , by(low_edu) 
	set scheme plotplainblind

	graph hbar pcthos, over(low_edu, relabel(1 "High-education" 2 "Low-education" ))  ///
    ytitle("% of children with a hospitalization") 
	graph export "$output/figure A1a_SES.pdf",as(pdf) replace

	restore
	
	g occupation = 1 if highskilled_whitecollar== 1
	replace occupation = 2 if lowskilled_whitecollar == 1
	replace occupation = 3 if manualworkers ==1
	
	bysort occupation: egen totalhospitalizations_oc = total(age_firstinphospital !=.)
	g pcthosp_oc= (totalhospitalizations_oc/totalbirth)*100

	su pct*
	collapse pcthosp_oc , by(occupation) 
	set scheme plotplainblind

	graph hbar pcthosp_oc, over(occupation, relabel(1 "High-skilled" 2 "Low-skilled" 3 "Manual workers" ))  ///
    ytitle("% of children with a hospitalization") 
	graph export "$output/figure A1c_occupation.pdf",as(pdf) replace
	
	
	
}

 
* Figs b and d: mortality
{
use "$processed_data\clean_births.dta", clear
bys lapsi_shnro child_b_year : gen dup = cond(_N== 1,0,_n)
drop if dup != 0
drop dup
ren aiti_shnro shnro

* Child mortality data (these files contains information on mortality shocks)
local year_range 8714 1517 18
foreach range of local year_range {
	merge 1:1 lapsi_shnro using "$processed_data\\`range'child.dta",update
	drop if _merge==2
	drop _merge
}
ren shnro shnro_mother

*recode mortality (2 = 1) (3 = 0), gen(mortality_experienced)
gen mortality_experienced = date_mortality != .

* Sample Event Study Mortality
merge m:1 shnro_mother using "$processed_data\date_mortality.dta", nogen 
*bys sample_mortality_event : tab mortality_experienced _merge, m 

* Clean date_diagnosis
** Not Finnish
g nonfinnish =(finnish == 0)
replace nonfinnish = . if finnish == .
label var nonfinnish "Non-finnish"
** Single 
label var single "Single"
** Married
label var married "Married"

* merge mothers income
merge m:1 shnro_mother using ///
"$processed_data\mothers_income_diagnosis_mortality_all", keepusing(educ*) keep(1 3) nogen




* Implement conditions
drop if age_firstmortality > 18 & age_firstmortality < .



g totalbirth = _N
g low_edu = 1 if educ0 == 3 | educ0== 4 | educ0 == 5 
replace low_edu = 0 if educ0 != . & low_edu != 1
	drop if low_edu ==.
	

	preserve
	bysort low_edu: egen totalmortality = total(age_firstmortality !=.)
	g pctmort= (totalmortality/totalbirth)*100

	su pct*
	collapse pctmort , by(low_edu) 
	set scheme plotplainblind

	graph hbar pctmort, over(low_edu, relabel(1 "High-education" 2"Low-education" ))  ///
    ytitle("% of children with a fatal shock") 
	graph export "$output/figure A1b_SES.pdf",as(pdf) replace

restore 

preserve
g occupation = 1 if highskilled_whitecollar== 1
	replace occupation = 2 if lowskilled_whitecollar == 1
	replace occupation = 3 if manualworkers ==1
	
	bysort occupation: egen totalmortality = total(age_firstmortality !=.)
	g pctmort= (totalmortality/totalbirth)*100

	su pct*
	collapse pctmort , by(occupation) 
	set scheme plotplainblind

	graph hbar pctmort, over(occupation, relabel(1 "High-skilled" 2 "Low-skilled" 3 "Manual workers" ))   ///
    ytitle("% of children with a fatal shock") 
	graph export "$output/figure A1d_occupation.pdf",as(pdf) replace
}


**********************************************************
* Figure A2: Differeces in Characteristis: Across Families
** (a) Finland
**********************************************************
{
    
* Import birth data
use "$processed_data\clean_births.dta", clear
bys lapsi_shnro child_b_year : gen dup = cond(_N== 1,0,_n)
drop if dup != 0
drop dup
ren aiti_shnro shnro_mother

* Merge overall data on births with datasets containing date of admission and dummy for hospitalization
** tupva: date of admission -- in 4.define_hospitalizations we keep the only 
** hospitalization for each child
local year_range 8793 9402 0310 2011 2012 2013 1417
** 87-93, 94-02, 03-10, 2011, 2012, 2013, 2014-2017
foreach range of local year_range {
    merge 1:1 lapsi_shnro using ///
		"$processed_data\d_inphospital`range'child.dta", update
		drop if _merge == 2
		drop _merge
}
** Change missings to 0
replace inphospital=0 if inphospital==.

* Sample Event Study Hospitalizations
merge m:1 shnro_mother using "$processed_data\date_diagnosis.dta", nogen 

* Generate age of first diagnosis
tab tupva_inphospital,m 
su age_firstinphospital
cap drop age_firstinphospital
gen age_firstinphospital=tupva_inphospital-child_b_date
replace age_firstinphospital=age_firstinphospital/365 // in years
su age_firstinphospital

* Clean date_diagnosis
** Not Finnish
g nonfinnish =(finnish == 0)
replace nonfinnish = . if finnish == .
label var nonfinnish "Non-finnish"
** Single 
label var single "Single"
** Married
label var married "Married"

* merge mothers income
merge m:1 shnro_mother using ///
"$processed_data\mothers_income_diagnosis_all", keepusing(educ*) keep(1 3) nogen 

* Implement conditions
drop if age_firstinphospital > 18 & age_firstinphospital < .
** Check
tab inphospital,m 
count if inphospital == 0 & !missing(age_firstinphospital)

local variables male gestation_weeks birth_weight ///
mother_age finnish nonfinnish single married  ///
educ1 educ2 educ3 educ4 educ5 educ6 ///
highskilled_whitecollar lowskilled_whitecollar manualworkers ///
selfemployed 

eststo clear
foreach var of local variables {
	egen `var'_z = std(`var')
	local label : variable label `var'
	label variable `var'_z `"`label'"'
}

foreach var of local variables {
	eststo `var':  reg `var'_z inphospital i.child_b_year , cluster(shnro_mother)
}

set scheme plotplainblind
coefplot male, bylabel("Male") ///
|| mother_age, bylabel("Mother age")  ///
|| nonfinnish, bylabel("Non-finnish") ///
|| single, bylabel("Single") ///
|| married, bylabel("Married") ///
|| educ1, bylabel("Secondary") ///
|| educ2, bylabel("Post-secondary") ///
|| educ3, bylabel("Short-cycle tertiary") ///
|| educ4, bylabel("Bachelor's") ///
|| educ5, bylabel("Master's") ///
|| educ6, bylabel("Doctoral") ///
|| highskilled_whitecollar,  bylabel("High-skilled") ///
|| lowskilled_whitecollar, bylabel("Low-skilled") ///
|| manualworkers, bylabel("Manual workers") ///
|| selfemployed, bylabel("Self-employed") ///
keep(inphospital)  xtitle( "Hospitalization" ) ///
xlabel(-0.15(0.10)0.15,nogrid) ylabel(,nogrid) ytitle("") ///
graphregion(color(white)) bgcolor(white) bycoefs xline(0, lcolor(black)) ///
ciopts(recast(rcap) color(black*0.5)) levels(95) aspectratio(1) ///
coeflabels(,labsize (small)) mcolor(black) msize(vsmall) msymbol(circle_hollow)
 
graph export "$output/figure A2_fi.pdf",as(pdf) replace

}

**********************************************************
* Figure A3: Mortality: Differences in Characteristics
** A: Across Families
** B: Within Affected Families
**********************************************************
{
* Import data and define variables
** Birth data
use "$processed_data\clean_births.dta", clear
bys lapsi_shnro child_b_year : gen dup = cond(_N== 1,0,_n)
drop if dup != 0
drop dup
ren aiti_shnro shnro

* Child mortality data (these files contains information on mortality shocks)
local year_range 8714 1517 18
foreach range of local year_range {
	merge 1:1 lapsi_shnro using "$processed_data\\`range'child.dta",update
	drop if _merge==2
	drop _merge
}
ren shnro shnro_mother

*recode mortality (2 = 1) (3 = 0), gen(mortality_experienced)
gen mortality_experienced = date_mortality != .

* Sample Event Study Mortality
merge m:1 shnro_mother using "$processed_data\date_mortality.dta", nogen 
*bys sample_mortality_event : tab mortality_experienced _merge, m 

* Clean date_diagnosis
** Not Finnish
g nonfinnish =(finnish == 0)
replace nonfinnish = . if finnish == .
label var nonfinnish "Non-finnish"
** Single 
label var single "Single"
** Married
label var married "Married"

* merge mothers income
merge m:1 shnro_mother using ///
"$processed_data\mothers_income_diagnosis_mortality_all", keepusing(educ*) keep(1 3) nogen

local variables male gestation_weeks birth_weight ///
mother_age finnish nonfinnish single married  ///
educ1 educ2 educ3 educ4 educ5 educ6 ///
highskilled_whitecollar lowskilled_whitecollar manualworkers ///
selfemployed ///

eststo clear
foreach var of local variables {
	egen `var'_z = std(`var')
	local label : variable label `var'
	label variable `var'_z `"`label'"'
}

foreach var of local variables {
	eststo `var':  reg `var'_z mortality_experienced i.child_b_year , cluster(shnro_mother)
}

esttab gestation_weeks birth_weight, keep(mortality_experienced) ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)

* Figure A1 (a)
set scheme plotplainblind
coefplot male, bylabel("Male") ///
|| mother_age, bylabel("Mother age")  ///
|| nonfinnish, bylabel("Non-finnish") ///
|| single, bylabel("Single") ///
|| married, bylabel("Married") ///
|| educ1, bylabel("Secondary") ///
|| educ2, bylabel("Post-secondary") ///
|| educ3, bylabel("Short-cycle tertiary") ///
|| educ4, bylabel("Bachelor's") ///
|| educ5, bylabel("Master's") ///
|| educ6, bylabel("Doctoral") ///
|| highskilled_whitecollar,  bylabel("High-skilled") ///
|| lowskilled_whitecollar, bylabel("Low-skilled") ///
|| manualworkers, bylabel("Manual workers") ///
|| selfemployed, bylabel("Self-employed") ///
keep(mortality_experienced)  xtitle("Fatal Shock") ///
xlabel(-0.2(0.10)0.2,nogrid) ylabel(,nogrid) ytitle("") ///
graphregion(color(white)) bgcolor(white) bycoefs xline(0, lcolor(black)) ///
ciopts(recast(rcap) color(black*0.5)) levels(95) aspectratio(1) ///
coeflabels(,labsize (small)) mcolor(black) msize(vsmall) msymbol(circle_hollow)

graph export "$output/figure A3a_fi.pdf", as(pdf) replace


* B: Matched Sample Data DiD Mortality
use "$processed_data\date_mortality.dta", clear 

keep if sample_mortality == 1 

** Clean date_diagnosis
*** Not Finnish
g nonfinnish =(finnish == 0)
replace nonfinnish = . if finnish == .
label var nonfinnish "Non-finnish"
*** Single 
label var single "Single"
*** Married
label var married "Married"

** merge mothers income
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4_mortality", keep(3) nogen
 
local variables male gestation_weeks birth_weight ///
mother_age finnish nonfinnish single married  ///
educ1 educ2 educ3 educ4 educ5 educ6 ///
highskilled_whitecollar lowskilled_whitecollar manualworkers ///
selfemployed

eststo clear
foreach var of local variables {
	egen `var'_z = std(`var')
	local label : variable label `var'
	label variable `var'_z `"`label'"'
}

foreach var of local variables {
	eststo `var':  reg `var'_z treat i.child_b_year, cluster(shnro_mother)
}

esttab gestation_weeks birth_weight, keep(treat) ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)

coefplot male, bylabel("Male") ///
|| mother_age, bylabel("Mother age")  ///
|| nonfinnish, bylabel("Non-finnish") ///
|| single, bylabel("Single") ///
|| married, bylabel("Married") ///
|| educ1, bylabel("Secondary") ///
|| educ2, bylabel("Post-secondary") ///
|| educ3, bylabel("Short-cycle tertiary") ///
|| educ4, bylabel("Bachelor's") ///
|| educ5, bylabel("Master's") ///
|| educ6, bylabel("Doctoral") ///
|| highskilled_whitecollar,  bylabel("High-skilled") ///
|| lowskilled_whitecollar, bylabel("Low-skilled") ///
|| manualworkers, bylabel("Manual workers") ///
|| selfemployed, bylabel("Self-employed") ///
keep(treat)  xtitle("Delta = 4") ///
xlabel(-0.2(0.10)0.2,nogrid) ylabel(,nogrid) ytitle("") ///
graphregion(color(white)) bgcolor(white) bycoefs xline(0, lcolor(black)) ///
ciopts(recast(rcap) color(black*0.5)) levels(95) aspectratio(1) ///
coeflabels(,labsize (small)) mcolor(black) msize(vsmall) msymbol(circle_hollow)

 
graph export "$output/figure A3b_fi.pdf", as(pdf) replace
}

**********************************************************
* Figure A4 : Number of Observations by Child's Age at Event Time 
** (a) Finland: hospitalizations
** (c) Finland: mortality 
**********************************************************
{
* (a) Finland: hospitalizations
use "$processed_data\date_diagnosis.dta", clear 

* restrict sample
keep if sample_hospital == 1
keep if inrange(age_firstinphospital, 7, 18)
su age_firstinphospital

* Figure A2a 
preserve 
replace age_firstinphospital = round(age_firstinphospital)
gen n = 1 
collapse (count) N=n, by(age_firstinphospital) 
su 
graph bar N, over(age_firstinphospital)  ///
ytitle("Number of observations") ascat 
graph export "$output/figure A4a_fi.pdf", as(pdf) replace
restore 


* (c) Finland: mortality 
use "$processed_data\date_mortality.dta", clear 

* restrict sample
keep if sample_mortality == 1
keep if inrange(age_firstmortality, 7, 18)
su age_firstmortality

* Figure A2c
preserve 
replace age_firstmortality = round(age_firstmortality)
gen n = 1 
collapse (count) N=n, by(age_firstmortality) 
su 
graph bar N, over(age_firstmortality)  ///
ytitle("Number of observations") ascat 
graph export "$output/figure A4c_fi.pdf", as(pdf) replace
restore 
}

**********************************************************
* Figure A5 : Descriptive: children born in 1990
** (a) Finland: hospitalizations
** (b) Finland: mortality 
** (c) Finland: hospitalizations by recurrence 
** (d) Number of stays
**********************************************************
{
    
* Prepare temporary data
use "$processed_data\clean_births.dta", clear
bys lapsi_shnro child_b_year : gen dup = cond(_N== 1,0,_n)
drop if dup != 0
drop dup
ren aiti_shnro shnro_mother

** Merge overall data on births with datasets containing date of admission and dummy for hospitalization (see 1.cleandata section 5)
local year_range 8793 9402 0310 2011 2012 2013 1417
foreach range of local year_range {
    merge 1:1 lapsi_shnro using ///
		"$processed_data\d_inphospital`range'child.dta", update
		drop if _merge == 2
		drop _merge
}
** Change missings to 0
replace inphospital=0 if inphospital==.


* Age of first diagnosis
gen age_firstinphospital=tupva_inphospital-child_b_date
replace age_firstinphospital=age_firstinphospital/365 // in years


** restrict sample (birthday)
keep if child_b_year== 1990

** Merge number of stays (which are at least a day long and are not from pregnancy)
/* There are children who have multiple hospital stays but are set to inphospital = 0
in the initial sample since their first hospitalization is considered a pregnancy
*/
merge 1:1 lapsi_shnro using "$processed_data\stays_all.dta"
drop if _merge == 2
replace n_stay = 0 if _merge == 1 //these are children who have not had any hospital vists
drop _merge
tab inphospital

** Subset variables 
keep shnro_mother lapsi_shnro child_b_year lengthstay inphospital ///
age_firstinphospital n_stay

save "$processed_data\temp.dta", replace 


	{
	* (a) Finland: hospitalizations
	use "$processed_data\temp.dta", clear 
	g totalbirth = _N

	** restrict sample (age of first diagnosis)
	keep if age_firstinphospital <= 18

	egen totalhospitalization = total(inphospital==1)
	g pctghospitalized = (totalhospitalization/totalbirth)*100
	egen totalbefore6 = total(inphospital==1 & age_firstinphospital < 7)
	g pctgbefore6 = (totalbefore6/totalbirth)*100
	egen totalafter6 = total(inphospital == 1 & age_firstinphospital >= 7)
	g pctgafter6 = (totalafter6/totalbirth)*100

	collapse pctghospitalized pctgbefore6 pctgafter6 , by(child_b_year) 
	graph bar pctghospitalized pctgbefore6 pctgafter6, ///
	title("(a) Hospitalizations by age group", size(medsmall)) ///
	ascat ytitle("% of children with a hospitalization", size(small)) ///
	yvaroptions(relabel(1 "All ages" 2 "Ages 0 to 6" 3 "Ages 7 to 18")) ///
	legend(off) name("a", replace)
	graph export "$output/figure A5a_fi.pdf", as(pdf) replace

	* (b) Finland: mortality

	** Import birth data 
	use "$processed_data\clean_births.dta", clear 
	bys lapsi_shnro child_b_year : gen dup = cond(_N== 1,0,_n)
	drop if dup != 0
	drop dup
	ren aiti_shnro shnro

	** Merge child mortality data (these files contains information on mortality shocks)
	merge 1:1 lapsi_shnro using "$processed_data\8714child.dta",update
	drop if _merge==2
	drop _merge
	merge 1:1 lapsi_shnro using "$processed_data\1517child.dta",update
	drop if _merge==2
	drop _merge
	merge 1:1 lapsi_shnro using "$processed_data\18child.dta", update
	drop if _merge==2
	drop _merge
	ren shnro shnro_mother

	g age_firstmortality = yearmortality - child_b_year

	** restrict sample (birth year)
	keep if child_b_year== 1990

	g totalbirth = _N
	** restrict sample (age of first diagnosis)
	keep if age_firstmortality <= 18
	  
	egen totalmortality = total(age_firstmortality !=.)
	g pctgmortality= (totalmortality/totalbirth)*100
	g mortality06 = 1 if age_firstmortality <7
	g mortality718 = 1 if age_firstmortality >= 7
	egen totalbefore6 = total(mortality06)
	g pctgbefore6 = (totalbefore6 /totalbirth)*100
	egen totalafter6 = total(mortality718)
	g pctgafter6 = (totalafter6 /totalbirth)*100

	su pct*
	collapse pctgmortality pctgbefore6 pctgafter6 , by(child_b_year) 
	graph bar pctgmortality pctgbefore6 pctgafter6 , ///
	title("(b) Mortality by age group", size(medsmall)) ///
	ascat ytitle("% of children with a fatal shock", size(small)) ///
	yvaroptions(relabel(1 "All ages" 2 "Ages 0 to 6" 3 "Ages 7 to 18")) ///
	legend(off) name("b", replace)
	graph export "$output/figure A5b_fi.pdf", as(pdf) replace

	* (c) Finland: hospitalizations by recurrence 
	use "$processed_data\temp.dta", clear 

	g totalbirth = _N

	keep if age_firstinphospital <= 18

	su age_firstinphospital, de 

	count if missing(age_firstinphospital)
	tab inphospital,m 
	gen age = round(age_firstinphospital)
	su age, de 
	gen bin1 = n_stay > 1

	collapse (sum) n_recur=bin1 n_hosp=inphospital, by(age totalbirth)
	gen pct_hosp = (n_hosp/totalbirth)*100
	gen pct_recur = (n_recur/totalbirth)*100
	egen x = sum(pct_hosp)
	gen share_rec = pct_recur/pct_hosp
	list 


	set scheme plotplainblind
	graph tw bar pct_hosp pct_recur age, title("") ///
	xtitle("Age", size(small)) xscale(range(0 18)) ///
	xlab(0(1)18, nogrid notick labsize(small)) ///
	title("(c) Hospitalization recurrence", size(medsmall)) ///
	ytitle("% of children with a hospitalization", size(small)) ylabel(, labsize(small)) ///
	graphregion(color(white)) bgcolor(white)  ///
	legend(rows(2) label(1 "% hospitalized") label(2 "% recurrent hospitalization") ///
	size(small) symysize(2) symxsize(2) position(6)) legend(off) name("c", replace)

	graph export "$output/figure A5c_fi.pdf", as(pdf) replace


	* (d) Number of stays
	** % of children ages 7 to 18 who have x amount of stays 

	use "$processed_data\temp.dta", clear
	keep if inrange(age_firstinphospital, 7,18)
	tab inphospital,m 

	gen bin1 = n_stay == 1
	gen bin2 = n_stay == 2
	gen bin3 = n_stay == 3
	gen bin4 = n_stay == 4
	gen bin5 = (n_stay >= 5)

	collapse (mean) bin*
	des bin*, varlist
	foreach var of varlist `r(varlist)' {
		replace `var' = `var'*100
	} 
	list 

	graph bar bin*, ascat ///
	title("(d) Number of stays", size(medsmall)) ///
	ytitle("% of children ages 7 to 18 who have x amount of stays", size(small)) ///
	yvaroptions(relabel(1 "1 stay" 2 "2 stays" ///
	3 "3 stays" 4 "4 stays" 5 " >= 5 stays")) legend(off) name("d", replace)

	graph export "$output/figure A5d_fi.pdf", as(pdf) replace


	** Combine all graphs
	graph combine a b c d, rows(2) title("") ///
	graphregion(color(white)) 
	graph export "$output/figure A5_fi.pdf",as(pdf) replace
	
	}

}

**********************************************************
* Figure A6 : Hospitalizations and Mortality Shocks by Main Diagnosis Group
** (a) Finland: hospitalizations
** (c) Finland: mortality 
**********************************************************
{
* (a) Finland: hospitalizations

use "$processed_data\matched_hg.dta", clear 
merge 1:1 shnro_mother using "$processed_data\date_diagnosis.dta", keepusing(sample_hospital) nogen 
keep if sample_hospital == 1

g agehosp = year(first_inphospital) - child_b_year
su agehosp,de
g yearinphospital = year(first_inphospital)

keep if inrange(agehosp, 7, 18)
gen n = 1 
graph hbar (sum) n, over(groups) ytitle("Number of observations")
graph export "$output/figure A6a_fi.pdf",as(pdf) replace

* (c) Finland: mortality 

** Import birth data 
use "$processed_data\clean_births.dta", clear 
bys lapsi_shnro child_b_year : gen dup = cond(_N== 1,0,_n)
drop if dup != 0
drop dup
ren aiti_shnro shnro

** Merge child mortality data (these files contains information on mortality shocks)
merge 1:1 lapsi_shnro using "$processed_data\8714child.dta",update
drop if _merge==2
drop _merge
merge 1:1 lapsi_shnro using "$processed_data\1517child.dta",update
drop if _merge==2
drop _merge
merge 1:1 lapsi_shnro using "$processed_data\18child.dta", update
drop if _merge==2
drop _merge
ren shnro shnro_mother

* gen first mortality per mother (if they have several kids diagnosed)
bys shnro_mother : egen first_mortality=min(date_mortality)
g age_firstmortality = yearmortality -child_b_year
drop if missing(age_firstmortality)

* keep one obs per mother
keep if first_mortality == date_mortality & date_mortality != .
bys shnro_mother (child_b_date) : gen twin = cond(_N== 1,0,_n)
drop if twin >= 1 & twin !=.
drop twin

merge 1:1 shnro_mother using "$processed_data\date_mortality.dta", keepusing(sample_mortality) keep(3) nogen 
keep if sample_mortality == 1

destring tpksaika, g (cause)
g groupcause = 1 if cause >= 1 & cause <= 3
replace groupcause = 2 if cause >= 4 & cause <= 22
replace groupcause = 3 if cause >= 23 & cause <= 24
replace groupcause = 4 if cause == 26
replace groupcause = 5 if cause >= 27 & cause <= 30 
replace groupcause = 6 if cause >= 31 & cause <= 35
replace groupcause = 7 if cause == 36 | cause == 37
replace groupcause = 8 if cause == 38
replace groupcause = 9 if cause == 39 | cause == 40 | cause == 41
replace groupcause = 10 if cause >= 42 & cause <= 53
	 

label define icd10 1 "Infections" 2 "Neoplasms" 3 "Endocrine" 4 "Nervous" ///
5 "Circulatory" 6 "Respiratory" 7 "Digestive or Genitourinary" 8 "Congenital" ///
9 "Other or unknown"  10 "Accidents"
label val groupcause icd10

tab yearmortality, m 
tab age_firstmortality,m 
** restrict sample 
keep if inrange(age_firstmortality,7,18)  
gen n = 1 
graph hbar (sum) n, over(groupcause) ytitle("Number of observations")
graph export "$output/figure A6c_fi.pdf",as(pdf) replace

}


**********************************************************
* Figure A7a : Hospitalizations Impact on Maternal Earnings
**********************************************************
{

use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Put in long format
drop married /* this variable comes from birth registry*/
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 income* father_income* divorced* married* unmarried* widowed* 

egen new_shnromother = group(shnro_mother treat)
reshape  long income_ father_income_ divorced_ married_ unmarried_ widowed_, ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename divorced_ divorced
rename married_ married
rename unmarried_ unmarried
rename widowed_ widowed

 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table 3
** Set controls
global controls i.treat i.age_mother i.age_father i.year_calendar ///
i.child_b_year i.educ0 i.father_educ0 male

** Implement conditions
keep if $sample_did
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat



** generate dummies for nonlinear effects for income
foreach var in income { 
gen `var'_mom1 = `var' if time_event == -2
bysort shnro_mother: egen `var'_mom2= max(`var'_mom1)
}


sum income if time_event == -2 , detail
g incomep10 = 1 if income < 900
replace incomep10 = 0 if income != . & incomep10 ==.
g incomep25 = 1 if income < 11700
replace incomep25 = 0 if income != . & incomep25 ==.
g incomep50 = 1 if income < 21400
replace incomep50 = 0 if income != . & incomep50 ==.
g incomep75 = 1 if income < 28700
replace incomep75 = 0 if income != . & incomep75 ==.
g incomep90 = 1 if income < 71000
replace incomep90 = 0 if income != . & incomep90 ==.




foreach var in incomep10 incomep25 incomep50 incomep75 incomep90 { 

** Income 
reg `var' post treat post_treat $controls, cluster(shnro_mother) coeflegend
estimates store income`var'
estadd local controls "YES"
sum `var' if time_event == -2
estadd scalar ymean = r(mean)

}

label var post_treat "Post x Treat"

set scheme plotplain
coefplot incomeincomep10, bylabel("p10") ///
|| incomeincomep25, bylabel("p25")  ///
|| incomeincomep50, bylabel("p50") ///
|| incomeincomep75, bylabel("p75") ///
|| incomeincomep90, bylabel("p90") ///
keep(post_treat)  xtitle("Post x Treat") ///
xlabel(-0.01(0.01)0.04,nogrid) ylabel(,nogrid) ytitle("") ///
graphregion(color(white)) bgcolor(white) bycoefs xline(0, lcolor(black)) ///
ciopts(recast(rcap) color(black*0.5)) levels(95) aspectratio(1) ///
coeflabels(,labsize (small)) mcolor(black) msize(vsmall) msymbol(circle_hollow)
 
 
graph export "$output/figure A7a_fipercentile.pdf",as(pdf) replace

}

**********************************************************
* Figure A7b : Mortality Impact on Maternal Earnings
**********************************************************
{
use "$processed_data\date_mortality.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4_mortality_acc", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4_mortality_acc", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 ///
transfers_* father_transfers* totalincome_* f_totalincome_* ///
income_* father_income_* fam_allow_* f_fam_allow_*

egen new_shnromother = group(shnro_mother treat)
reshape long transfers_ father_transfers_ totalincome_ ///
f_totalincome_ income_ father_income_ fam_allow_ f_fam_allow_, ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename transfers_ transfers
rename father_transfers_ father_transfers
rename totalincome_ totalincome
rename f_totalincome_ f_totalincome
rename fam_allow_ fam_allow
rename f_fam_allow_ f_fam_allow
 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

** Set controls
global controls_mothers i.treat i.age_mother i.year_calendar ///
i.child_b_year male
global controls_fathers i.treat i.age_father i.year_calendar ///
i.child_b_year male

** Restrict sample 
keep if $sample_is_mortality
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat


g income_mf= income + father_income
g totalincome_mf = totalincome + f_totalincome
g transfers_mf = transfers + father_transfers
g fam_allow_mf = fam_allow + f_fam_allow





** generate dummies for nonlinear effects for income
foreach var in income { 
gen `var'_mom1 = `var' if time_event == -2
bysort shnro_mother: egen `var'_mom2= max(`var'_mom1)
}


sum income if time_event == -2 , detail
g incomep10 = 1 if income <= 0
replace incomep10 = 0 if income != . & incomep10 ==.
g incomep25 = 1 if income < 8000
replace incomep25 = 0 if income != . & incomep25 ==.
g incomep50 = 1 if income < 21100
replace incomep50 = 0 if income != . & incomep50 ==.
g incomep75 = 1 if income < 27300
replace incomep75 = 0 if income != . & incomep75 ==.
g incomep90 = 1 if income < 36400
replace incomep90 = 0 if income != . & incomep90 ==.


/* By maternal income percentile */

foreach var in incomep10 incomep25 incomep50 incomep75 incomep90 { 

** Income 
reg `var' post treat post_treat $controls, cluster(shnro_mother) coeflegend
estimates store income`var'
estadd local controls "YES"
sum `var' if time_event == -2
estadd scalar ymean = r(mean)

}

label var post_treat "Post x Treat"
set scheme plotplain
coefplot incomeincomep10, bylabel("p10") ///
|| incomeincomep25, bylabel("p25")  ///
|| incomeincomep50, bylabel("p50") ///
|| incomeincomep75, bylabel("p75") ///
|| incomeincomep90, bylabel("p90") ///
keep(post_treat)  xtitle("Post x Treat") ///
xlabel(-0.04(0.04)0.16,nogrid) ylabel(,nogrid) ytitle("") ///
graphregion(color(white)) bgcolor(white) bycoefs xline(0, lcolor(black)) ///
ciopts(recast(rcap) color(black*0.5)) levels(95) aspectratio(1) ///
coeflabels(,labsize (small)) mcolor(black) msize(vsmall) msymbol(circle_hollow)
 
 
graph export "$output/figure A7b_fipercentile_mort.pdf",as(pdf) replace


}



**********************************************************
* Figure A9 : Hospitalizations Children's Number of Visits
**********************************************************
{
* Import inpatient and outpatient hospitalization data 
use "$processed_data\matched.dta", clear
merge 1:m lapsi_shnro using "$processed_data\visits_onlydate.dta"
keep if _merge == 3
drop _merge

g year_visit=year(tupva_visit)

*counts visits per year and mother 
bys shnro_mother year_visit: egen n_visit_year=count(year_visit)

g yearinphospital=year(first_inphospital)

* variables for number of visits years before and after health shock
keep shnro_mother child_b_year year_visit n_visit_year yearinph ///
first_inphospital  mother_b_year father_b_year shnro_father
*one obs per mother and year of diagnosis
collapse (first) n_visit_year child_b_year yearinph first_inphospital ///
mother_b_year father_b_year shnro_father,by(shnro_mother year_visit)
*put in wide format
reshape wide n_visit_year,i(shnro_mother) j(year_visit)
*substitute missings with 0's
foreach y of numlist 1990(1)2017{
	replace n_visit_year`y'=0 if n_visit_year`y'==.
}

forvalues x=0(1)10{
g visitsyear`x'=.
}

forvalues y=1990(1)2017{
	forvalues x= 0(1)10{
		local year=`y'+`x'
		if `y'<=(2016-`x'){
			replace visitsyear`x'=n_visit_year`year' if yearinph==`y'
		}
	}
}

* calculate mhealth visits in x years before (to chck pretrends)
forvalues x=1(1)5{
g visitsyearminus`x'=.
}

forvalues y=1990(1)2017{
	forvalues x= 1(1)5{
		local year=`y'-`x'
		if `year'>=1990{
			replace visitsyearminus`x'=n_visit_year`year' if yearinph==`y'
		}
	}
}

reshape long visits, i(shnro_mother) j(year_event) string

gen time_event=.
forvalues x=0(1)4{
	replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
}

lab var time_event "Years with respect to shock"

* Restrict sample 
keep if inrange(time_event, -5, 3) 

preserve 
collapse (mean) visits,by(time_event)
set scheme plotplainblind
graph set window fontface "Times New Roman"
twoway ///
  (scatter visits time_event, msymbol(circle) mcolor(gs8) lcolor(gs8)), ///
  ytitle("Average Number of Child Medical Visits", size(medsmall)) ///
  xtitle("Event time (years)") xline(-0.5,lcolor(black)) ///
  xlabel(-5(1)3,nogrid) ylabel(,nogrid) ///
  graphregion(color(white)) legend(off) bgcolor(white)
  
graph export "$output/figure A9_fi.pdf",as(pdf) replace
restore 
}

**********************************************************
* Figure A10a: Hospitalizatins: Type of health shocks (by diagnosis code)
**********************************************************
{

use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Put in long format
drop married /* this variable comes from birth registry*/
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 income* father_income* divorced* married* unmarried* widowed* ICD10

egen new_shnromother = group(shnro_mother treat)
reshape  long income_ father_income_ divorced_ married_ unmarried_ widowed_, ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename divorced_ divorced
rename married_ married
rename unmarried_ unmarried
rename widowed_ widowed

 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table 3
** Set controls
global controls i.treat i.age_mother i.age_father i.year_calendar ///
i.child_b_year i.educ0 i.father_educ0 male

** Implement conditions
keep if $sample_did
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat



* Generate high-level subgroups
g grouponly = substr(ICD10,1,2) 
g icd10_group = 1 if substr(grouponly,1,1) == "A" | substr(grouponly,1,1) == "B" 
replace icd10_group = 2 if substr(grouponly,1,1) == "C"
replace icd10_group = 2 if substr(grouponly,1,2) == "D1" | ///
substr(grouponly,1,2) == "D2" | substr(grouponly,1,2) == "D3" | ///
substr(grouponly,1,2) == "D4"   
replace icd10_group = 3 if substr(grouponly,1,1) == "D" & icd10_group != 2
replace icd10_group = 4 if substr(grouponly,1,1) == "E"
replace icd10_group = 5 if substr(grouponly,1,1) == "F"
replace icd10_group = 6 if substr(grouponly,1,1) == "G"
replace icd10_group = 7 if substr(grouponly,1,2) == "H1" | ///
substr(grouponly,1,2) == "H2" | substr(grouponly,1,2) == "H3" | ///
substr(grouponly,1,2) == "H4"   | substr(grouponly,1,2) == "H5"
replace icd10_group = 8 if substr(grouponly,1,1) == "H" & icd10_group != 7
replace icd10_group = 9 if substr(grouponly,1,1) == "I"
replace icd10_group = 10 if substr(grouponly,1,1) == "J"
replace icd10_group = 11 if substr(grouponly,1,1) == "K"
replace icd10_group = 12 if substr(grouponly,1,1) == "L"
replace icd10_group = 13 if substr(grouponly,1,1) == "M"
replace icd10_group = 14 if substr(grouponly,1,1) == "N"
replace icd10_group = 15 if substr(grouponly,1,1) == "O"
replace icd10_group = 17 if substr(grouponly,1,1) == "Q"
replace icd10_group = 18 if substr(grouponly,1,1) == "R"
replace icd10_group = 19 if substr(grouponly,1,1) == "S" | ///
substr(grouponly,1,1) == "T"
replace icd10_group = 21 if substr(grouponly,1,1) == "Z"
* Note: group 20 only one observation
label define icd10 1 "Infections" 2 "Neoplasms" 3 "Blood" ///
4 "Endocrine" 5 "Mental" 6 "Nervous" 7 "Eye" 8 "Ear" 9 "Circulatory" ///
10 "Respiratory" 11 "Digestive" 12 "Skin" 13 "Muscoloskeletal" ///
14 "Genitourinary" 17 "Congenital" ///
18 "Symptoms" 19 "Injury" 21 "Factors", replace 
label val icd10_group icd10
tab icd10_group,m 
drop grouponly


foreach var in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 17 18 19 21  { 


** Income 
reg income post treat post_treat $controls if icd10_group == `var' , cluster(shnro_mother) coeflegend
estimates store income`var'
estadd local controls "YES"
sum income if time_event == -2 & icd10_group == `var' 
estadd scalar ymean = r(mean)

}

* plot 
set scheme plotplain
coefplot income1, bylabel("Infections") ///
|| income2, bylabel("Neoplasms") ///
|| income3, bylabel("Blood") ///
|| income4, bylabel("Endocrine") ///
|| income5, bylabel("Mental") ///
|| income6, bylabel("Nervous") ///
|| income7, bylabel("Eye") ///
|| income8, bylabel("Ear") ///
|| income9, bylabel("Circulatory") ///
|| income10, bylabel("Respiratory") ///
|| income11, bylabel("Digestive") ///
|| income12, bylabel("Skin") ///
|| income13, bylabel("Muscoloskeletal") ///
|| income14, bylabel("Genitourinary") ///
|| income17, bylabel("Congenital") ///
|| income18, bylabel("Symptoms") ///
|| income19, bylabel("Injury") ///
|| income21, bylabel("Factors") ///
keep(post_treat)  xtitle("Post x Treat") ///
xlabel(-4000(1000)4000,nogrid) ylabel(,nogrid) ytitle("") ///
graphregion(color(white)) bgcolor(white) bycoefs xline(0, lcolor(black)) ///
ciopts(recast(rcap) color(black*0.5)) levels(95) aspectratio(1) ///
coeflabels(,labsize (small)) mcolor(black) msize(vsmall) msymbol(circle_hollow)
 
 
graph export "$output/figure A10a_fi.pdf",as(pdf) replace
}


**********************************************************
*  Figure A10b: Hospitalizatins: Type of health shocks (by chrnocitity of health condition)
**********************************************************
{
	
clear
import delimited ///
"W:\Ramon\Child_Health_Shocks\info\classification_chronic_conditions.csv", ///
varnames(1) 

des, f

* Clean variables
** Chronic Indicator 
replace chronicindicator = subinstr(chronicindicator, "'", "",.)
destring chronicindicator, replace 
tab chronicindicator,m 

** body system
tab bodysystem,m 
replace bodysystem = subinstr(bodysystem, "'", "",.)
replace bodysystem = "" if bodysystem == "None"
destring bodysystem, replace 
tab bodysystem,m 

** icd10 
gen icd10 = subinstr(icd10cmcode, "'", "",.)
rename icd10 ICD10

list in 1/10

keep ICD10 chronicindicator

save "$processed_data\chronic_conditions.dta", replace 

* Merge with overall data 

use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4", keep(3) nogen 
* merge with chronic indicator list 
merge m:1 ICD10 using  "$processed_data\chronic_conditions.dta"
drop if _merge == 2
drop _merge

* Put in long format
drop married /* this variable comes from birth registry*/
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 income* father_income* divorced* married* unmarried* widowed* ICD10 chronicindicator

egen new_shnromother = group(shnro_mother treat)
reshape  long income_ father_income_ divorced_ married_ unmarried_ widowed_, ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename divorced_ divorced
rename married_ married
rename unmarried_ unmarried
rename widowed_ widowed

 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table 3
** Set controls
global controls i.treat i.age_mother i.age_father i.year_calendar ///
i.child_b_year i.educ0 i.father_educ0 male

** Implement conditions
keep if $sample_did
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat



foreach var in 0 1 { 


** Income 
reg income post treat post_treat $controls if chronicindicator == `var' , cluster(shnro_mother) coeflegend
estimates store income`var'
estadd local controls "YES"
sum income if time_event == -2 & chronicindicator == `var' 
estadd scalar ymean = r(mean)

}


* plot 
set scheme plotplain
coefplot income0, bylabel("Non-chronic") ///
|| income1, bylabel("Chronic") ///
keep(post_treat)  xtitle("Post x Treat") ///
xlabel(-1500(500)1500,nogrid) ylabel(,nogrid) ytitle("") ///
graphregion(color(white)) bgcolor(white) bycoefs xline(0, lcolor(black)) ///
ciopts(recast(rcap) color(black*0.5)) levels(95) aspectratio(1) ///
coeflabels(,labsize (small)) mcolor(black) msize(vsmall) msymbol(circle_hollow)
 
 
graph export "$output/figure A10b_fi.pdf",as(pdf) replace
}


**********************************************************
* Figure A11: Mental Health: Mediation Analysis
**********************************************************
{
    
use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4", keep(3) nogen  
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
mentalhealth* educ0 child_b_year income_* father_income_* ///
father_educ0 male treat ageinptreat year_treat
rename mentalhealthdad* dadmentalhealth*

egen new_shnromother = group (shnro_mother treat)
reshape long mentalhealth dadmentalhealth income_ father_income_, i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income

* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
	replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
	g even`i'_treat = i_time_even_`i'*treat
	label var even`i'_treat "`time_to_shock'"
	local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
	local x = `i' + 6 
	label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
	local x =  6 - `i'
	label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Figure A6, Panel A
** Set controls
global controls i.treat i.age_mother i.age_father ///
i.year_calendar i.child_b_year i.educ0 i.father_educ0 male

** Restrict sample 
keep if $sample_mh
rename mentalhealth* Tmentalhealth*
estimates clear 

* Generate probability of MH visit 
** Overall
g Tprob_mentalhealth = (Tmentalhealth > 0)
replace Tprob_mentalhealth = . if Tmentalhealth == .


** Probability of mental health visit: ONE OVERALL MEDIATOR
*** Unconditional effect
reg income $event_dummies $event_treat_dummies $controls, cluster(shnro_mother)
forval i = 6/9 {
	global beta`i' = _b[even`i'_treat]
}
*** Conditional effect 
reg income $event_dummies $event_treat_dummies Tprob_mentalhealth $controls, cluster(shnro_mother)
global phi_mh = _b[Tprob_mentalhealth]

*** Effect of the treatment on the mediator
reg Tprob_mentalhealth $event_dummies $event_treat_dummies $controls ///
if !missing(income), cluster(shnro_mother)

*** Compute fraction of treatment mediated for each time-period
forval i = 6/9 {
	global beta_m`i' = _b[even`i'_treat]

	local numerator = ${beta_m`i'}* ${phi_mh}
	
	local frac`i' = ((${beta_m`i'} * ${phi_mh}) / ${beta`i'}) * 100
	
	cap drop Frac`i'
	gen Frac`i' = `frac`i''
	
}

*** Calculate unexplained variation
forval i = 6/9 {
	cap drop unexp_frac`i'
	gen unexp_frac`i' = 100 - Frac`i'
}

su Frac6-unexp_frac9


graph set window fontface "Times New Roman"

preserve 
collapse (first) Frac6-unexp_frac9
gen x = _n 
reshape long Frac unexp_frac, i(x) j(time_event)
replace x = _n 
list 
cap label drop x_lab
label define x_lab 1 "Year of hospitalization" 2 "1 year after hospitalization" ///
3 "2 years after hospitalization" 4 "3 years after hospitalization"
label values x x_lab 

graph hbar Frac unexp_frac, over(x, label(labsize(vsmall))) stack graphregion(color(white)) ///
ylabel(, labsize(small) grid) ytitle("Percent", size(small)) ///
bar(1, lwidth(none) fcolor(gs2)) bar(2, lwidth(none) fcolor(gs10)) ///
legend(region(col(none)) position(6) label(1 "Mental Health Visit") ///
label(2 "Unexplained") size(small)) title("(a) Hospitalizations", size(medsmall)) ///
name(hosp, replace)
restore 


* Mortality 
use "$processed_data\date_mortality.dta", clear 
merge 1:m shnro_mother using "$processed_data\mothers_income_diagnosis4_mortality_acc", keep(3) nogen  
merge 1:1 shnro_mother treat using "$processed_data\fathers_income_diagnosis4_mortality_acc", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
mentalhealth* educ0 child_b_year income_* father_income_* ///
father_educ0 male treat ageinptreat year_treat
rename mentalhealthdad* dadmentalhealth*

egen new_shnromother = group (shnro_mother treat)
reshape long mentalhealth dadmentalhealth income_ father_income_, i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income

* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
	replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
	g even`i'_treat = i_time_even_`i'*treat
	label var even`i'_treat "`time_to_shock'"
	local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
	local x = `i' + 6 
	label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
	local x =  6 - `i'
	label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 


* Figure A6, Panel B 
** Set controls
global controls_mother i.treat i.age_mother ///
i.year_calendar i.child_b_year male

** Restrict sample 
keep if $sample_mh_mortality
rename mentalhealth* Tmentalhealth*
estimates clear 

* Generate probability of MH visit 
** Overall
g Tprob_mentalhealth = (Tmentalhealth > 0)
replace Tprob_mentalhealth = . if Tmentalhealth == .


** Probability of mental health visit: ONE OVERALL MEDIATOR
*** Unconditional effect
reg income $event_dummies $event_treat_dummies $controls_mother, cluster(shnro_mother)
forval i = 6/9 {
	global beta`i' = _b[even`i'_treat]
}
*** Conditional effect 
reg income $event_dummies $event_treat_dummies Tprob_mentalhealth $controls_mother, cluster(shnro_mother)
global phi_mh = _b[Tprob_mentalhealth]

*** Effect of the treatment on the mediator
reg Tprob_mentalhealth $event_dummies $event_treat_dummies $controls_mother ///
if !missing(income), cluster(shnro_mother)

*** Compute fraction of treatment mediated for each time-period
forval i = 6/9 {
	global beta_m`i' = _b[even`i'_treat]

	local numerator = ${beta_m`i'}* ${phi_mh}
	
	local frac`i' = ((${beta_m`i'} * ${phi_mh}) / ${beta`i'}) * 100
	
	cap drop Frac`i'
	gen Frac`i' = `frac`i''
	
}

*** Calculate unexplained variation
forval i = 6/9 {
	cap drop unexp_frac`i'
	gen unexp_frac`i' = 100 - Frac`i'
}

su Frac6-unexp_frac9


graph set window fontface "Times New Roman"

preserve 
collapse (first) Frac6-unexp_frac9
gen x = _n 
reshape long Frac unexp_frac, i(x) j(time_event)
replace x = _n 
list 
cap label drop x_lab
label define x_lab 1 "Year of fatal shock" 2 "1 year after fatal shock" ///
3 "2 years after fatal shock" 4 "3 years after fatal shock   "
label values x x_lab 

graph hbar Frac unexp_frac, over(x, label(labsize(vsmall))) stack graphregion(color(white)) ///
ylabel(, labsize(small) grid) ytitle("Percent", size(small)) ///
bar(1, lwidth(none) fcolor(gs2)) bar(2, lwidth(none) fcolor(gs10)) ///
legend(region(col(none)) position(6) label(1 "Mental Health Visit") ///
label(2 "Unexplained") size(small)) title("(b) Mortality", size(medsmall)) name(mort, replace)

restore 

grc1leg2 hosp mort, cols(1) legendfrom(hosp) title("") ///
graphregion(color(white)) 
graph display, ysize(5) xsize(5.5)  margins(small)
graph export "$output/figure A11_fi.pdf",as(pdf) replace

}


**********************************************************
* Figure A13 : Hospitalizations: Probability of Divorce 
* Figure A14: Hospitalizations: Choice of Work Environment and Changing Jobs
* Table 3 columns (2,3,4)
**********************************************************
{
use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using "$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using "$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
divorced_year* public_year* changejob_year* ///
father_divorced_year* father_public_year* father_changejob_year* ///
educ0 father_educ0 male treat ///
ageinptreat year_treat income_* father_income_* child_b_year

egen new_shnromother = group (shnro_mother treat)
reshape long divorced_ public_ changejob_ father_divorced_ father_public_ ///
father_changejob_ income_ father_income_,i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename divorced_ divorced
rename public_ public
rename changejob_ changejob
rename father_divorced_ father_divorced
rename father_public_ father_public
rename father_changejob_ father_changejob 

* gen numeric variable for time w.r.t  hospitalization
gen time_event=.
forvalues x=0(1)3{
	replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
	g even`i'_treat = i_time_even_`i'*treat
	label var even`i'_treat "`time_to_shock'"
	local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
	local x = `i' + 6 
	label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
	local x =  6 - `i'
	label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* generate post dummy
gen post = time_event >= 0
tab post 
* generate post*treat interaction dummy
gen posttreat = post*treat 


* Figure A13
** Set controls
global controls i.treat i.age_mother i.age_father ///
i.year_calendar i.child_b_year i.educ0 i.father_educ0 male

** Restrict sample 
keep if $sample_did

estimates clear 
reg divorced $event_dummies $event_treat_dummies $controls ///
if !missing(divorced) & !missing(father_divorced), cluster(shnro_mother) 
estimates store divorcedmom

** coefficients of time to event
gen coef_event_timed=.
g boundLd = .
g boundHd = .
foreach x of numlist 1/3 5/9{
replace coef_event_timed=_b[even`x'_treat] if time_event==(`x'-6)
replace boundLd = _b[even`x'_treat] -1.96*_se[even`x'_treat] if time_event==(`x'-6)
replace boundHd = _b[even`x'_treat] + 1.96*_se[even`x'_treat] if time_event==(`x'-6)
}
replace coef_event_timed=0 if time_event==-2 // omitted category, -2

preserve
collapse  coef_event_timed boundHd boundLd ,by(time_event)
twoway (rspike boundLd boundHd time_event, color(gs8*0.5) ///
lcolor(gs8*0.5) pstyle(p1)) (scatter coef_event_timed time_event, ///
msymbol(circle) mcolor(gs8) lcolor(gs8)), ytitle("Prob of divorce", size(medsmall)) ///
xtitle("Event time (years)") xline(-0.5,lcolor(black)) ///
xlabel(-5(1)3,nogrid) ylabel(0.03(0.02)-0.03, nogrid) ///
yline(0, lpattern(dash) lcolor(black)) ylabel(, nogrid) ///
graphregion(color(white)) legend(off) bgcolor(white)

graph export "$output/figure A13_fi.pdf",as(pdf) replace
restore



* Figure A14a
reg public $event_dummies $event_treat_dummies $controls ///
if !missing(public) & !missing(father_public), cluster(shnro_mother) 
estimates store publicmom

** coefficients of time to event
gen coef_event_timep=.
g boundLp = .
g boundHp = .
foreach x of numlist 1/3 5/9{
replace coef_event_timep=_b[even`x'_treat] if time_event==(`x'-6)
replace boundLp = _b[even`x'_treat] -1.96*_se[even`x'_treat] if time_event==(`x'-6)
replace boundHp = _b[even`x'_treat] + 1.96*_se[even`x'_treat] if time_event==(`x'-6)
}
replace coef_event_timep=0 if time_event==-2 // omitted category, -2

preserve
collapse  coef_event_timep  boundHp boundLp ,by(time_event)

twoway (rspike boundLp boundHp time_event, color(gs8*0.5) ///
lcolor(gs8*0.5) pstyle(p1)) (scatter coef_event_timep time_event, ///
msymbol(circle) mcolor(gs8) lcolor(gs8)), ///
ytitle("Prob of public-sector work", size(medsmall)) xtitle("Event time (years)") ///
xline(-0.5,lcolor(black)) xlabel(-5(1)3,nogrid) ylabel(0.03(0.02)-0.03, nogrid) ///
yline(0, lpattern(dash) lcolor(black)) ylabel(, nogrid) ///
graphregion(color(white)) legend(off) bgcolor(white)

graph export "$output/figure A14a_fi.pdf",as(pdf) replace
restore

* Figure A14b
reg changejob $event_dummies $event_treat_dummies $controls ///
if !missing(changejob) & !missing(father_changejob), cluster(shnro_mother) 
estimates store jobmom

** coefficients of time to event
gen coef_event_timec=.
g boundLc = .
g boundHc = .
foreach x of numlist 1/3 5/9{
replace coef_event_timec=_b[even`x'_treat] if time_event==(`x'-6)
replace boundLc = _b[even`x'_treat] -1.96*_se[even`x'_treat] if time_event==(`x'-6)
replace boundHc = _b[even`x'_treat] + 1.96*_se[even`x'_treat] if time_event==(`x'-6)
}
replace coef_event_timec=0 if time_event==-2 // omitted category, -2

preserve
collapse  coef_event_timec  boundHc boundLc ,by(time_event)

twoway (rspike boundLc boundHc time_event, color(gs8*0.5) ///
lcolor(gs8*0.5) pstyle(p1)) (scatter coef_event_timec time_event, msymbol(circle) ///
mcolor(gs8) lcolor(gs8)), ytitle("Prob of changing job", size(medsmall)) ///
xtitle("Event time (years)") xline(-0.5,lcolor(black)) xlabel(-5(1)3,nogrid) ///
ylabel(0.03(0.02)-0.03, nogrid) yline(0, lpattern(dash) lcolor(black)) ///
ylabel(, nogrid) graphregion(color(white)) legend(off) bgcolor(white)

graph export "$output/figure A14b_fi.pdf", as(pdf) replace
restore


* Table 3 columns (2) (3) and (4):

foreach var in divorced public changejob {
** Average effects
reg  `var' post treat posttreat $controls, cluster(shnro_mother)
	estimates store `var'_mom
	estadd local controls "YES"
	sum  `var' if time_event == -2
	estadd scalar ymean = r(mean)
	

}


** Output
esttab divorced_mom public_mom changejob_mom ///
using "$output\table 3b_fi.tex", label replace ///
addnotes("This table shows the impact of children's hospital admission on the probability of divorce, working in a public enterprise, or changing jobs. The table shows the estimated coefficients for the interaction between the post and the treat dummy. We use administrative data from Finland. All specifications include controls for calendar year, child's year of birth, child's gender, and each parent's age and educational level. Standard erros are clustered at the parent level.'") ///
mtitles("Divorce" "Public-sector" "Changing jobs") ///
keep(posttreat) ///
scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)
}







************************************************
* Summary statistics - Table A2
************************************************
{
    
* Sample Event Study Hospitalizations *
eststo clear 

* IMPORT DATA AND MERGE 
use "$processed_data\date_diagnosis.dta", clear

** Implement sample conditions
keep if sample_hospital_event == 1

** merge mothers income
merge 1:1 shnro_mother using "$processed_data\mothers_income_diagnosis_all", keep(3) nogen
** merge fathers income
merge 1:1 shnro_mother using "$processed_data\fathers_income_diagnosis_all", keep(3) nogen

* Summary stats 
eststo : estpost sum $vars

************************************************
* Matched Sample Data DiD Hospitalizations *

* IMPORT DATA AND MERGE 
use "$processed_data\date_diagnosis.dta", clear 

** Implement sample conditions
keep if sample_hospital == 1

** merge mothers income
merge 1:m shnro_mother using "$processed_data\mothers_income_diagnosis4", keep(3) nogen
** merge fathers income
merge 1:1 shnro_mother treat using "$processed_data\fathers_income_diagnosis4", keep(3) nogen

drop age_firstinphospital
rename ageinphospitalnew age_firstinphospital

* Summary stats 
eststo : estpost sum $vars

************************************************
* Sample Event Study Mortality*

* IMPORT DATA AND MERGE
use "$processed_data\date_mortality.dta", clear 

* Implement conditions
keep if sample_mortality_event == 1 

** merge mothers income
merge 1:1 shnro_mother using ///
"$processed_data\mothers_income_diagnosis_mortality_all", keep(3) nogen
** merge fathers income
merge 1:1 shnro_mother ///
using "$processed_data\fathers_income_diagnosis_mortality_all", keep(3) nogen

rename age_firstmortality age_firstinphospital

* Summary stats 
eststo : estpost sum $vars

************************************************
* Matched Sample Data DiD Mortality *

* IMPORT DATA AND MERGE 
use "$processed_data\date_mortality.dta", clear 

* Implement sample conditions
keep if sample_mortality == 1 

** merge mothers income
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4_mortality", nogen keep(3)
** merge fathers income
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4_mortality", nogen keep(3)

rename agemortalitynew age_firstinphospital

* Summary stats 
eststo : estpost sum $vars

************************************************
* Output *
esttab est2 est1 est4 est3 using "$output/Table A2_sumstats_fi.tex", ///
cells("mean(fmt(%9.3f)) sd(fmt(%9.3f))") label replace ///
title("Summary statistics all hospitalizations") ///
mtitles("Matched Sample DiD Hospitalizations" "Sample Event Study Hospitalizations" ///
"Matched Sample DiD Mortality" "Sample Event Study Mortality") booktabs

}


**********************************************************
* Table A4: Hospitalizations: Mothers' Labor Outcomes
**********************************************************
{
    
use "$processed_data\date_diagnosis.dta", clear 

merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4", keep(3) nogen
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Subset variables
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp income_* ///
father_income_* educ0 child_b_year father_educ0 male treat ageinptreat year_treat ///
nchild_year*

egen new_shnromother = group(shnro_mother treat)
reshape long income_ father_income_, ///
i(new_shnromother) j(year_event) string
drop new_shnromother
rename income_ income
rename father_income_ father_income
 

* gen numeric variable for time w.r.t  to the hospitalization
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* generate post dummy
gen post = time_event >= 0
tab post 
* generate post*treat interaction dummy
gen posttreat = post*treat 
	
* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table 1
** Set controls
global controls i.treat i.age_mother i.age_father ///
i.year_calendar i.child_b_year i.educ0 i.father_educ0 male

** Implement conditions
keep if $sample_did

estimates clear 
** Earnings (Euro)
reg income $event_dummies $event_treat_dummies $controls, cluster(shnro_mother)
estimates store incomemom
estadd local controls "YES"
sum income if time_event == -2
estadd scalar ymean = r(mean)

** Earnings (%)
*** Mothers Income as percentage of time at -2
egen mean_minus1_ = mean(income) if time_event == -2
replace mean_minus1_ = 0 if mean_minus1_ == .
egen mean_minus1 = max(mean_minus1_)

gen income_pct = (income/mean_minus1)*100
reg income_pct $event_dummies $event_treat_dummies $controls, cluster(shnro_mother)
estimates store incomemompct
estadd local controls "YES"
sum income_pct if time_event == -2
estadd scalar ymean = r(mean)


** Working probability
*** definition as in norwegian data:
g working2 = (income > 0 ) if !missing(income)
reg working2 $event_dummies $event_treat_dummies $controls, cluster(shnro_mother) 
estimates store workingmom
estadd local controls "YES"
sum working2 if time_event == -2
estadd scalar ymean = r(mean)

**** Output Mothers: tex
esttab incomemom incomemompct workingmom ///
using "$output\table A4_fi.tex", label replace ///
addnotes("This table shows the impact of a child's hospitalization on maternal earnings (Euro) (in column (1)), maternal earnings as a \% of mean earnings in $t-2$ (in column (2)), and maternal working probability (in column (3)), for both Finalnd and Norway. The table shows the estimated coefficients for the interaction between the event time dummies and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Earnings (\euro)" "Earnings (\%)" "Employment") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean $Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)


}

**********************************************************
* Table A5: Hospitalizations: DID vs Event Study 
**********************************************************
{
* Differnce in Differences with Delta = 4 
use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4", keep(3) nogen 

keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp income_* ///
father_income_* educ0 child_b_year father_educ0 male treat ageinptreat year_treat

egen new_shnromother = group(shnro_mother treat)
reshape long income_ father_income_, ///
i(new_shnromother) j(year_event) string
drop new_shnromother
rename income_ income
rename father_income_ father_income
 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
	replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
	g even`i'_treat = i_time_even_`i'*treat
	label var even`i'_treat "`time_to_shock'"
	local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
	local x = `i' + 6 
	label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
	local x =  6 - `i'
	label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table A4
** Set controls
global controls i.treat i.age_mother i.age_father ///
i.year_calendar i.child_b_year i.educ0 i.father_educ0 male

** Restrict sample 
keep if $sample_did

estimates clear 

** Earnings (Euro)
reg income $event_dummies $event_treat_dummies $controls, cluster(shnro_mother)
estimates store incomemom
estadd local controls "YES"
sum income if time_event == -2
estadd scalar ymean = r(mean)

* Event Study Inidividual FE w. Sun & Abraham adj

** IMPORT DATA AND MERGE 
use "$processed_data\date_diagnosis.dta", clear

** merge mothers income
merge 1:1 shnro_mother using "$processed_data\mothers_income_diagnosis_all", keep(3) nogen
merge 1:1 shnro_mother using "$processed_data\fathers_income_diagnosis_all", keep(3) nogen

keep yearinp shnro_mother shnro_father ///
income_* father_income_* age_firstinphospital

reshape long income_ father_income_,i(shnro_mother) j(year_event) string
rename income_ income
rename father_income_ father_income

** gen numeric variable for time w.r.t health shock (health shock year==0)
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

** gen year of income (calendar year)
gen year_calendar=yearinp+time_event

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization"

** Restrict sample 
keep if $sample_event

** Generate numeric ids to control for individual fixed effects
encode shnro_mother, g (mother_id)
drop if missing(shnro_father)
encode shnro_father, g(father_id)

** last cohort of children affected will be the control group for A&S 
g last_cohort = 1 if yearinp == 2014
replace last_cohort = 0 if last_cohort ==.

eventstudyinteract income $event_dummies if year_calendar < 2014,  cohort(yearinp) ///
control_cohort(last_cohort) ///
absorb(i.mother_id i.year_calendar) vce(cluster mother_id)

estimates store incomeeventmom
estadd local controls "YES"
sum income if time_event == -2
estadd scalar ymean = r(mean)

** Output 
esttab incomemom incomeeventmom ///
using "$output\Table A5_fi.tex", label replace ///
addnotes("This table shows the impact of a child's hospitalization on maternal earnings (Euro) using the differences-in-differences specification in equation 1 (in column (1)), and using the event study approach with individual fixed effects laid out in equation (2) (in column (2)), for both Finland and Norway. For the event study, we implement the IW estimator proposed by ?. Clustered standard errors at the parent level.") ///
mtitles("Earnings DiD (\euro)" "Earnings FE (\euro)") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat ) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)


}

**********************************************************
* Table A6: Mortality: Mothers' Labor Outcomes
**********************************************************
{
use "$processed_data\date_mortality.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4_mortality_acc",nogen keep(3)
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4_mortality_acc", nogen keep(3)

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp income_* ///
father_income_* educ0 child_b_year father_educ0 male treat ageinptreat year_treat

egen new_shnromother = group(shnro_mother treat)
reshape long income_ father_income_ ,i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income

* gen numeric variable for time w.r.t the hospitalization
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* generate post dummy
gen post = time_event >= 0
tab post 
* generate post*treat interaction dummy
gen posttreat = post*treat 

* Table 2
** Set controls
global controls_mother i.treat i.age_mother i.year_calendar ///
i.child_b_year male

** Implement conditions
keep if $sample_did_mortality

estimates clear 
** Earnings (Euro)
reg income $event_dummies $event_treat_dummies $controls_mother, ///
cluster(shnro_mother)
estimates store incomemom
estadd local controls "YES"
sum income if time_event == -2
estadd scalar ymean = r(mean)

** Earnings (%)
*** Mothers Income as percentage of time at -2
egen mean_minus1_ = mean(income) if time_event == -2
replace mean_minus1_ = 0 if mean_minus1_ == .
egen mean_minus1 = max(mean_minus1_)

gen income_pct = (income/mean_minus1)*100
reg income_pct $event_dummies $event_treat_dummies $controls_mother, cluster(shnro_mother)
estimates store incomemompct
estadd local controls "YES"
sum income_pct if time_event == -2
estadd scalar ymean = r(mean)

** Working probability
*** definition as in norwegian data:
g working2 = (income > 0 ) if !missing(income)
reg working2 $event_dummies $event_treat_dummies $controls_mother, cluster(shnro_mother) 
estimates store workingmom
estadd local controls "YES"
sum working2 if time_event == -2
estadd scalar ymean = r(mean)

**** Output Mothers: tex, smcl 
esttab incomemom incomemompct workingmom ///
using "$output\table A6_fi.tex", label replace ///
addnotes("This table shows the impact of a child's fatal shock on maternal earnings (Euro) (in column (1)), maternal earnings as a \% of mean earnings in $t-2$ (in column (2)), and maternal working probability (in column (3)). We use administrative data from Finland and the sample includes all fatal shocks due to injuries, poisonings, or other consequences of external causes. The table shows the estimated coefficients for the interaction between the event time dummies and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Earnings (\euro)" "Earnings (\%)" "Employment") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) ///
scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)




}

**********************************************************
* Table A7: Hospitalizations: Fathers' Labor Outcomes
**********************************************************
{
use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using "$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using "$processed_data\fathers_income_diagnosis4", keep(3) nogen 

keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp income_* ///
father_income_* educ0 child_b_year father_educ0 male treat ageinptreat year_treat

egen new_shnromother = group(shnro_mother treat)
reshape long income_ father_income_, ///
i(new_shnromother) j(year_event) string
drop new_shnromother
rename income_ income
rename father_income_ father_income
 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
	replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
	g even`i'_treat = i_time_even_`i'*treat
	label var even`i'_treat "`time_to_shock'"
	local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
	local x = `i' + 6 
	label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
	local x =  6 - `i'
	label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* generate post dummy
gen post = time_event >= 0
tab post 
* generate post*treat interaction dummy
gen posttreat = post*treat 
	
	
* Table A5 - Finnish part
** Set controls
global controls i.treat i.age_mother i.age_father ///
i.year_calendar i.child_b_year i.educ0 i.father_educ0 male

** Implement conditions
keep if $sample_did

estimates clear 

** Earnings (Euro)
reg father_income $event_dummies $event_treat_dummies $controls, ///
cluster(shnro_father)
estimates store incomedad
estadd local controls "YES"
sum father_income if time_event == -2
estadd scalar ymean = r(mean)

** Earnings (%)
*** Father's Income as percentage of time at -2
egen mean_minus1f_ = mean(father_income) if time_event == -2
replace mean_minus1f_ = 0 if mean_minus1f_ == .
egen mean_minus1f = max(mean_minus1f_)

gen father_income_pct = (father_income/mean_minus1f)*100
reg father_income_pct $event_dummies $event_treat_dummies $controls, ///
cluster(shnro_father)
estimates store incomedadpct
estadd local controls "YES"
sum father_income_pct if time_event == -2
estadd scalar ymean = r(mean)

** Working probability
*** definition as in norwegian data:
g father_working2 = (father_income > 0 ) if !missing(father_income)
reg father_working2 $event_dummies $event_treat_dummies $controls, cluster(shnro_father) 
estimates store workingdad
estadd local controls "YES"
sum father_working2 if time_event == -2
estadd scalar ymean = r(mean)


** Output
esttab incomedad incomedadpct workingdad ///
using "$output\Table A7_fi.tex", label replace ///
addnotes("This table shows the impact of a child's hospitalization on father's earnings (Euro) (in column (1)), earnings as a \% of mean earnings in $t-2$ (in column (2)), and working probability (in column (3)), for both Finalnd and Norway. The table shows the estimated coefficients for the interaction between the event time dummies and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Earnings (\euro)" "Earnings (\%)" "Employment") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean $Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)

esttab incomedad incomedadpct workingdad ///
using "$output\Table A7_fi", label replace ///
addnotes("This table shows the impact of a child's hospitalization on father's earnings (Euro) (in column (1)), earnings as a \% of mean earnings in $t-2$ (in column (2)), and working probability (in column (3)), for both Finalnd and Norway. The table shows the estimated coefficients for the interaction between the event time dummies and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Earnings (\euro)" "Earnings (\%)" "Employment") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean $Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) smcl

}

**********************************************************
* Table A8: Mortality: Fathers' Labor Outcomes
**********************************************************
{
    
use "$processed_data\date_mortality.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4_mortality_acc", nogen keep(3)
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4_mortality_acc", nogen keep(3)
 
* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp income_* ///
father_income_* educ0 child_b_year father_educ0 male treat ageinptreat year_treat

egen new_shnromother = group(shnro_mother treat)
reshape long income_ father_income_ ,i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income

* gen time event 
gen time_event=.
forvalues x=0(1)3{
	replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat+time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar-mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
	g even`i'_treat = i_time_even_`i'*treat
	label var even`i'_treat "`time_to_shock'"
	local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
	local x = `i' + 6 
	label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
	local x =  6 - `i'
	label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization"

* generate post dummy
gen post = time_event >= 0
tab post 
* generate post*treat interaction dummy
gen posttreat = post*treat 
	 

* Table A6 - each year separately
** Set controls
global controls_father i.treat i.age_father ///
i.year_calendar i.child_b_year male

** Implement conditions
keep if $sample_did_mortality

estimates clear 

** Earnings (Euro)
reg father_income $event_dummies $event_treat_dummies $controls_father, cluster(shnro_father)
estimates store incomedad
estadd local controls "YES"
sum father_income if time_event == -2
estadd scalar ymean = r(mean)

** Earnings (%)
*** Father's Income as percentage of time at -2
egen mean_minus1f_ = mean(father_income) if time_event == -2
replace mean_minus1f_ = 0 if mean_minus1f_ == .
egen mean_minus1f = max(mean_minus1f_)

gen father_income_pct = (father_income/mean_minus1f)*100
reg father_income_pct $event_dummies $event_treat_dummies $controls_father, cluster(shnro_father)
estimates store incomedadpct
estadd local controls "YES"
sum father_income_pct if time_event == -2
estadd scalar ymean = r(mean)

** Working probability
*** definition as in norwegian data:
g father_working2 = (father_income > 0 ) if !missing(father_income)
reg father_working2 $event_dummies $event_treat_dummies $controls_father, cluster(shnro_father) 
estimates store workingdad
estadd local controls "YES"
sum father_working2 if time_event == -2
estadd scalar ymean = r(mean)


** Output
esttab incomedad incomedadpct workingdad ///
using "$output\Table A8_fi.tex", label replace ///
addnotes("This table shows the impact of a child's fatal shock on father's earnings (Euro) (in column (1)), earnings as a \% of mean earnings in $t-2$ (in column (2)), and working probability (in column (3)). We use administrative data from Finland and the sample includes all fatal shocks due to injuries, poisonings, or other consequences of external causes. The table shows the estimated coefficients for the interaction between the event time dummies and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Earnings (\euro)" "Earnings (\%)" "Employment") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean $Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)

esttab incomedad incomedadpct workingdad ///
using "$output\Table A8_fi", label replace ///
addnotes("This table shows the impact of a child's fatal shock on father's earnings (Euro) (in column (1)), earnings as a \% of mean earnings in $t-2$ (in column (2)), and working probability (in column (3)). We use administrative data from Finland and the sample includes all fatal shocks due to injuries, poisonings, or other consequences of external causes. The table shows the estimated coefficients for the interaction between the event time dummies and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Earnings (\euro)" "Earnings (\%)" "Employment") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean $Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) smcl



* Table A6 - average post*treat effect
** Set controls
global controls_father i.post i.treat i.age_father ///
i.year_calendar i.child_b_year male

** Implement conditions
keep if $sample_did_mortality

estimates clear 

** Earnings (Euro)
reg father_income posttreat $controls_father, cluster(shnro_father)
estimates store incomedad_avg
estadd local controls "YES"
sum father_income if time_event == -2
estadd scalar ymean = r(mean)

** Earnings (%)
reg father_income_pct posttreat $controls_father, cluster(shnro_father)
estimates store incomedadpct_avg
estadd local controls "YES"
sum father_income_pct if time_event == -2
estadd scalar ymean = r(mean)

** Working probability
reg father_working2 posttreat $controls_father, cluster(shnro_father) 
estimates store workingdad_avg
estadd local controls "YES"
sum father_working2 if time_event == -2
estadd scalar ymean = r(mean)


** Output
esttab incomedad_avg incomedadpct_avg workingdad_avg ///
using "$output\Table A8_avg_fi.tex", label replace ///
addnotes("This table shows the impact of a child's fatal shock on father's earnings (Euro) (in column (1)), earnings as a \% of mean earnings in $t-2$ (in column (2)), and working probability (in column (3)). We use administrative data from Finland and the sample includes all fatal shocks due to injuries, poisonings, or other consequences of external causes. The table shows the estimated coefficients for the interaction between the post-event dummy and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Earnings (\euro)" "Earnings (\%)" "Employment") ///
keep(posttreat) scalars ("controls Controls" "ymean Mean $Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)

esttab incomedad_avg incomedadpct_avg workingdad_avg ///
using "$output\Table A8_avg_fi", label replace ///
addnotes("This table shows the impact of a child's fatal shock on father's earnings (Euro) (in column (1)), earnings as a \% of mean earnings in $t-2$ (in column (2)), and working probability (in column (3)). We use administrative data from Finland and the sample includes all fatal shocks due to injuries, poisonings, or other consequences of external causes. The table shows the estimated coefficients for the interaction between the post-event dummy and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Earnings (\euro)" "Earnings (\%)" "Employment") ///
keep(posttreat) scalars ("controls Controls" "ymean Mean $Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) smcl
}

**********************************************************
* Table A9: Hospitalizations: Fathers' Institutional Support 
**********************************************************
{
use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using "$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using "$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 ///
transfers_* father_transfers* totalincome_* f_totalincome_* ///
income_* father_income_* fam_allow_* f_fam_allow_*

egen new_shnromother = group(shnro_mother treat)
reshape long transfers_ father_transfers_ totalincome_ ///
f_totalincome_ income_ father_income_ fam_allow_ f_fam_allow_, ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename transfers_ transfers
rename father_transfers_ father_transfers
rename totalincome_ totalincome
rename f_totalincome_ f_totalincome
rename fam_allow_ fam_allow
rename f_fam_allow_ f_fam_allow
 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table A9
** Set controls
global controls i.treat i.age_mother i.age_father i.year_calendar ///
i.child_b_year i.educ0 i.father_educ0 male

** Restrict sample 
keep if $sample_is
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat

** Total income (euro)
reg father_income post treat post_treat $controls, vce(cluster shnro_father)
estimates store incomedad1
estadd local controls "YES"
sum father_income if time_event == -2
estadd scalar ymean = r(mean)

** Total income (euro)
reg f_totalincome post treat post_treat $controls, vce(cluster shnro_father)
estimates store incomedad
estadd local controls "YES"
sum f_totalincome if time_event == -2
estadd scalar ymean = r(mean)

** Transfers (euro)
reg father_transfers post treat post_treat $controls, cluster(shnro_father)
estimates store transfersdad
estadd local controls "YES"
sum father_transfers if time_event == -2 
estadd scalar ymean = r(mean)

** Allowance (euro)
reg f_fam_allow post treat post_treat $controls, cluster(shnro_father)
estimates store allowdad
estadd local controls "YES"
sum f_fam_allow if time_event == -2
estadd scalar ymean = r(mean)

* Output Fathers 
esttab incomedad1 incomedad transfersdad allowdad ///
using "$output\Table A9_fi.tex", label replace ///
addnotes("This table shows the impact of a child's hospitalization on father's total income (in column (1)), transfers received by the father (in column (2)), and family allowance (in column (3)), for both Finland and Norway, respectively. The table shows the coefficient for the interaction between a post dummy (after hospitalization) and the treat dummy in equation \ref{didequation}. All specificiations include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Income (\euro)" "Total Income (\euro)" "Transfers (\euro)" ///
"Family Allowance (\euro)") ///
keep(post_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$")  ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)


}


**********************************************************
* Table A10: Hospitalizations: Family income and Institutional support 
**********************************************************
{



use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 ///
transfers_* father_transfers* totalincome_* f_totalincome_* ///
income_* father_income_* fam_allow_* f_fam_allow_*

egen new_shnromother = group(shnro_mother treat)
reshape long transfers_ father_transfers_ totalincome_ ///
f_totalincome_ income_ father_income_ fam_allow_ f_fam_allow_, ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename transfers_ transfers
rename father_transfers_ father_transfers
rename totalincome_ totalincome
rename f_totalincome_ f_totalincome
rename fam_allow_ fam_allow
rename f_fam_allow_ f_fam_allow
 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table A10
** Set controls
global controls i.treat i.age_mother i.age_father i.year_calendar ///
i.child_b_year i.educ0 i.father_educ0 male

** Implement conditions
keep if $sample_is
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat

g income_mf= income + father_income
g totalincome_mf = totalincome + f_totalincome
g transfers_mf = transfers + father_transfers
g fam_allow_mf = fam_allow + f_fam_allow


** Income (euro)
reg income_mf post treat post_treat $controls, cluster(shnro_mother) coeflegend
estimates store incomemom
estadd local controls "YES"
sum income_mf if time_event == -2 
estadd scalar ymean = r(mean)

** Total income (euro)
reg totalincome_mf post treat post_treat $controls, cluster(shnro_mother) coeflegend
estimates store totalincomemom
estadd local controls "YES"
sum totalincome_mf if time_event == -2 
estadd scalar ymean = r(mean)

** Transfers (euro)
reg transfers_mf  post treat post_treat $controls, cluster(shnro_mother) coeflegend
estimates store transfersmom
estadd local controls "YES"
sum transfers_mf if time_event == -2 
estadd scalar ymean = r(mean)

** Allowance (euro)
reg fam_allow_mf  post treat post_treat $controls, cluster(shnro_mother) coeflegend
estimates store allowmom
estadd local controls "YES"
sum fam_allow_mf if time_event == -2 
estadd scalar ymean = r(mean)

* Output Mothers 
esttab incomemom totalincomemom transfersmom allowmom ///
using "$output\table A10_familyincome.tex", label replace ///
addnotes("This table shows the impact of a child's hospitalization on family earnings (in column (1)) family total income (in column (2)), family transfers received (in column (3)), and total family allowance (in column (4)), for both Finland and Norway, respectively. The table shows the coefficient for the interaction between a post dummy (after hospitalization) and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Family earnings (\euro)" "Family Total Income (\euro)" "Family Transfers (\euro)" ///
"Total Family Allowance (\euro)") ///
keep(post_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) 


}

**********************************************************
* Table A11: Mortality: Both Parents Institutional Support 
**********************************************************
{
use "$processed_data\date_mortality.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4_mortality_acc", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4_mortality_acc", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 ///
transfers_* father_transfers* totalincome_* f_totalincome_* ///
income_* father_income_* fam_allow_* f_fam_allow_*

egen new_shnromother = group(shnro_mother treat)
reshape long transfers_ father_transfers_ totalincome_ ///
f_totalincome_ income_ father_income_ fam_allow_ f_fam_allow_, ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename transfers_ transfers
rename father_transfers_ father_transfers
rename totalincome_ totalincome
rename f_totalincome_ f_totalincome
rename fam_allow_ fam_allow
rename f_fam_allow_ f_fam_allow
 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table A11
** Set controls
global controls_mothers i.treat i.age_mother i.year_calendar ///
i.child_b_year male
global controls_fathers i.treat i.age_father i.year_calendar ///
i.child_b_year male

** Restrict sample 
keep if $sample_is_mortality
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat

** Mothers
*** Income (euro)
reg income post treat post_treat $controls_mothers, cluster(shnro_mother)
estimates store incomemom0
estadd local controls "YES"
sum income if time_event == -2
estadd scalar ymean = r(mean)

*** Total income (euro)
reg totalincome post treat post_treat $controls_mothers, cluster(shnro_mother)
estimates store incomemom
estadd local controls "YES"
sum totalincome if time_event == -2
estadd scalar ymean = r(mean)

*** Transfers (euro)
reg transfers post treat post_treat $controls_mothers, cluster(shnro_mother)
estimates store transfersmom
estadd local controls "YES"
sum transfers if time_event == -2 
estadd scalar ymean = r(mean)

*** Allowance (euro)
reg fam_allow post treat post_treat $controls_mothers, cluster(shnro_mother)
estimates store allowmom
estadd local controls "YES"
sum fam_allow if time_event == -2 
estadd scalar ymean = r(mean)

*** Fathers
*** Income (euro)
reg father_income post treat post_treat $controls_fathers, vce(cluster shnro_father)
estimates store incomedad1
estadd local controls "YES"
sum father_income if time_event == -2
estadd scalar ymean = r(mean)

*** Total income (euro)
reg f_totalincome post treat post_treat $controls_fathers, vce(cluster shnro_father)
estimates store incomedad
estadd local controls "YES"
sum f_totalincome if time_event == -2
estadd scalar ymean = r(mean)

*** Transfers (euro)
reg father_transfers post treat post_treat $controls_fathers, cluster(shnro_father)
estimates store transfersdad
estadd local controls "YES"
sum father_transfers if time_event == -2 
estadd scalar ymean = r(mean)

*** Allowance (euro)
reg f_fam_allow  post treat post_treat $controls_fathers, cluster(shnro_father)
estimates store allowdad
estadd local controls "YES"
sum f_fam_allow if time_event == -2
estadd scalar ymean = r(mean)

** Output
esttab incomemom0 incomedad1 incomemom incomedad transfersmom transfersdad allowmom allowdad ///
using "$output\Table A11_fi.tex", label replace ///
addnotes("This table shows the impact of a child's fatal shock on income (in column (1)) total income (in column (2)), transfers received (in column (3)), and family allowance (in column (4)), for both mothers and fathers, respectively. The table shows the coefficient for the interaction between a post dummy (after hospitalization) and the treat dummy in equation \ref{didequation}. We use administrative data from Finland and the sample includes all fatal shocks due to accidents. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Income Mom (\euro)" "Income Dad (\euro)" "Total Income Mom (\euro)" "Total Income Dad (\euro)" "Transfers Mom (\euro)" ///
"Transfers Dad (\euro)" "Family Allowance Mom (\euro)" "Family Allowance Dad (\euro)") ///
keep(post_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)

esttab incomemom0 incomedad1 incomemom incomedad transfersmom transfersdad allowmom allowdad ///
using "$output\Table A11_fi", label replace ///
addnotes("This table shows the impact of a child's fatal shock on income (in column (1)) total income (in column (2)), transfers received (in column (3)), and family allowance (in column (4)), for both mothers and fathers, respectively. The table shows the coefficient for the interaction between a post dummy (after hospitalization) and the treat dummy in equation \ref{didequation}. We use administrative data from Finland and the sample includes all fatal shocks due to accidents. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Income Mom (\euro)" "Income Dad (\euro)" "Total Income Mom (\euro)" "Total Income Dad (\euro)" "Transfers Mom (\euro)" ///
"Transfers Dad (\euro)" "Family Allowance Mom (\euro)" "Family Allowance Dad (\euro)") ///
keep(post_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) smcl
}

**********************************************************
* Table A12: Mortality: Family Earnings + Institutional Support 
**********************************************************
{
use "$processed_data\date_mortality.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4_mortality_acc", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4_mortality_acc", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 ///
transfers_* father_transfers* totalincome_* f_totalincome_* ///
income_* father_income_* fam_allow_* f_fam_allow_*

egen new_shnromother = group(shnro_mother treat)
reshape long transfers_ father_transfers_ totalincome_ ///
f_totalincome_ income_ father_income_ fam_allow_ f_fam_allow_, ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename transfers_ transfers
rename father_transfers_ father_transfers
rename totalincome_ totalincome
rename f_totalincome_ f_totalincome
rename fam_allow_ fam_allow
rename f_fam_allow_ f_fam_allow
 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table A8
** Set controls
global controls_mothers i.treat i.age_mother i.year_calendar ///
i.child_b_year male
global controls_fathers i.treat i.age_father i.year_calendar ///
i.child_b_year male

** Restrict sample 
keep if $sample_is_mortality
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat


g income_mf= income + father_income
g totalincome_mf = totalincome + f_totalincome
g transfers_mf = transfers + father_transfers
g fam_allow_mf = fam_allow + f_fam_allow


** Mothers
*** Income (euro)
reg income_mf post treat post_treat $controls_mothers, cluster(shnro_mother)
estimates store incomemom0
estadd local controls "YES"
sum income_mf if time_event == -2
estadd scalar ymean = r(mean)

*** Total income (euro)
reg totalincome_mf post treat post_treat $controls_mothers, cluster(shnro_mother)
estimates store incomemom
estadd local controls "YES"
sum totalincome_mf if time_event == -2
estadd scalar ymean = r(mean)

*** Transfers (euro)
reg transfers_mf post treat post_treat $controls_mothers, cluster(shnro_mother)
estimates store transfersmom
estadd local controls "YES"
sum transfers_mf if time_event == -2 
estadd scalar ymean = r(mean)

*** Allowance (euro)
reg fam_allow_mf post treat post_treat $controls_mothers, cluster(shnro_mother)
estimates store allowmom
estadd local controls "YES"
sum fam_allow_mf if time_event == -2 
estadd scalar ymean = r(mean)


** Output
esttab incomemom0  incomemom  transfersmom allowmom ///
using "$output\tab A12_fi.tex", label replace ///
addnotes("This table shows the impact of a child's fatal shock on income (in column (1)) total income (in column (2)), transfers received (in column (3)), and family allowance (in column (4)), for both mothers and fathers, respectively. The table shows the coefficient for the interaction between a post dummy (after hospitalization) and the treat dummy in equation \ref{didequation}. We use administrative data from Finland and the sample includes all fatal shocks due to accidents. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Income Family (\euro)" "Total Income Family (\euro)" "Transfers Family (\euro)" ///
 "Family Allowance (\euro)" ) ///
keep(post_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)

}


**********************************************************
* Table A14: Hospitalizations: Choice of Delta
**********************************************************
{
    
estimates clear 
forvalues delta = 2/4 {
    
	use "$processed_data\date_diagnosis.dta", clear 
	merge 1:m shnro_mother using ///
	"$processed_data\mothers_income_diagnosis`delta'", keep(3) nogen 
	merge 1:1 shnro_mother treat using ///
	"$processed_data\fathers_income_diagnosis`delta'", keep(3) nogen 

	* Put in long format
	keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
	child_b_year male treat ageinptreat year_treat educ0 father_educ0 ///
	income_* father_income_*

	egen new_shnromother = group(shnro_mother treat)
	reshape long income_ father_income_, i(new_shnromother) j(year_event) string
	rename income_ income
	rename father_income_ father_income
	
	* gen numeric variable for time w.r.t the hospitalization?
	gen time_event=.
	forvalues x=0(1)3{
	replace time_event=`x' if year_event=="year`x'"
	}
	forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
	}

	* gen year of income (calendar year)
	gen year_calendar=year_treat + time_event

	* gen age of mother in each year
	gen mother_b_year=year_treat - age_mother_inp
	gen age_mother=year_calendar - mother_b_year

	* gen age of father in each year
	gen father_b_year=year_treat - age_father_inp
	gen age_father=year_calendar - father_b_year

	* dummify time_event, with -2 as omitted variable
	** all but i_time_even_4 (-2 time_event)
	xi i.time_event,prefix("i_") noomit
	global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
	i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

	* g interactions 
	local time_to_shock = -5 
	forvalues i= 1(1)9{
	g even`i'_treat = i_time_even_`i'*treat
	label var even`i'_treat "`time_to_shock'"
	local ++time_to_shock 
	}

	** all but i_time_even_4 (-2 time_event)
	global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
	even6_treat even7_treat even8_treat even9_treat

	forvalues i= 1(1)3{
	local x = `i' + 6 
	label var i_time_even_`x' "`i' years after hospitalization" 
	}
	forvalues i= 1(1)5 {
	local x =  6 - `i'
	label var i_time_even_`i' "`x' years before hospitalization"
	}

	label var i_time_even_6 "Year of hospitalization" 
	
	* Table 4
	** Set controls
	global controls i.treat i.age_mother i.age_father ///
	i.year_calendar i.child_b_year i.educ0 i.father_educ0 male

	** Implement conditions
	keep if $sample_did
	keep if time_event < `delta'
	
	** Earnings (Euro)
	reg income $event_dummies $event_treat_dummies $controls, cluster(shnro_mother)
	estimates store incomemom`delta'
	estadd local controls "YES"
	sum income if time_event == -2
	estadd scalar ymean = r(mean)

}

**** Output: tex 
esttab incomemom2 incomemom3 incomemom4 ///
using "$output\table A14_fi.tex", label replace ///
addnotes("This table shows the impact of childrens hospital admission on maternal earnings (Euro) using different deltas to define treatment and control.") ///
mtitles("Delta = 2" "Delta = 3" "Delta = 4") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)

}

**********************************************************
* Table A15: Mortality: Different control groups
**********************************************************
{
estimates clear 
forvalues delta = 2/4 {
    
	use "$processed_data\date_mortality.dta", clear 
	merge 1:m shnro_mother using ///
	"$processed_data\mothers_income_diagnosis`delta'_mortality_acc", keep(3) nogen 
	merge 1:1 shnro_mother treat using ///
	"$processed_data\fathers_income_diagnosis`delta'_mortality_acc", keep(3) nogen 

	
	* Put in long format
	keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
	child_b_year male treat ageinptreat year_treat educ0 father_educ0 ///
	income_* father_income_*

	egen new_shnromother = group(shnro_mother treat)
	reshape long income_ father_income_, i(new_shnromother) j(year_event) string
	rename income_ income
	rename father_income_ father_income
	
	* gen numeric variable for time w.r.t hospitalization 
	gen time_event=.
	forvalues x=0(1)3{
	replace time_event=`x' if year_event=="year`x'"
	}
	forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
	}

	* gen year of income (calendar year)
	gen year_calendar=year_treat + time_event

	* gen age of mother in each year
	gen mother_b_year=year_treat - age_mother_inp
	gen age_mother=year_calendar - mother_b_year

	* gen age of father in each year
	gen father_b_year=year_treat - age_father_inp
	gen age_father=year_calendar - father_b_year

	* dummify time_event, with -2 as omitted variable
	** all but i_time_even_4 (-2 time_event)
	xi i.time_event,prefix("i_") noomit
	global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
	i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

	* g interactions 
	local time_to_shock = -5 
	forvalues i= 1(1)9{
	g even`i'_treat = i_time_even_`i'*treat
	label var even`i'_treat "`time_to_shock'"
	local ++time_to_shock 
	}

	** all but i_time_even_4 (-2 time_event)
	global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
	even6_treat even7_treat even8_treat even9_treat

	forvalues i= 1(1)3{
	local x = `i' + 6 
	label var i_time_even_`x' "`i' years after hospitalization" 
	}
	forvalues i= 1(1)5 {
	local x =  6 - `i'
	label var i_time_even_`i' "`x' years before hospitalization"
	}

	label var i_time_even_6 "Year of hospitalization"

	* Table A9
	** Set controls
	global controls_mother i.treat i.age_mother ///
	i.year_calendar i.child_b_year male

	** Implement conditions
	keep if $sample_did_mortality
	keep if time_event < `delta'
	
	** Earnings (Euro)
	reg income $event_dummies $event_treat_dummies $controls_mother, cluster(shnro_mother)
	estimates store incomemom`delta'
	estadd local controls "YES"
	sum income if time_event == -2
	estadd scalar ymean = r(mean)

}

* Output: tex, smcl 
esttab incomemom2 incomemom3 incomemom4 ///
using "$output\Table A15_fi.tex", label replace ///
addnotes("This table shows the impact of a child's fatal shock on maternal labor earnings for different choices of control group. In column 1 we show the estimation results when the control group consists of families who experienced the child's hospitalization two years later, in column 2 three years later, and four years later in column 3 (our main specification). The table shows the estimated coefficients for the interaction between the event time dummies and the treat dummy in \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Delta = 2" "Delta = 3" "Delta = 4") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)

esttab incomemom2 incomemom3 incomemom4  ///
using "$output\Table A15_fi", label replace ///
addnotes("This table shows the impact of a child's fatal shock on maternal labor earnings for different choices of control group. In column 1 we show the estimation results when the control group consists of families who experienced the child's hospitalization two years later, in column 2 three years later, and four years later in column 3 (our main specification). The table shows the estimated coefficients for the interaction between the event time dummies and the treat dummy in \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Delta = 2" "Delta = 3" "Delta = 4") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) smcl
}

**********************************************************
* Table A16: Robustness: Mutual Shocks
**********************************************************
{
estimates clear
foreach time in week month {
	
	use "$processed_data\date_diagnosis.dta", clear 
	merge 1:m shnro_mother using ///
	"$processed_data\mothers_income_diagnosis4_`time'", keep(3) nogen 
	merge 1:1 shnro_mother treat using ///
	"$processed_data\fathers_income_diagnosis4_`time'", keep(3) nogen 

	* Put in long format
	keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
	child_b_year male treat ageinptreat year_treat educ0 father_educ0 ///
	income_* father_income_*

	egen new_shnromother = group(shnro_mother treat)
	reshape long income_ father_income_, i(new_shnromother) j(year_event) string
	rename income_ income
	rename father_income_ father_income
	
	 
	* gen numeric variable for time w.r.t hospitalization
	gen time_event=.
	forvalues x=0(1)3{
		replace time_event=`x' if year_event=="year`x'"
	}
	forvalues x=1(1)5{
		replace time_event=-`x' if year_event=="yearminus`x'"
	}

	* gen year of income (calendar year)
	gen year_calendar=year_treat + time_event

	* gen age of mother in each year
	gen mother_b_year=year_treat - age_mother_inp
	gen age_mother=year_calendar - mother_b_year

	* gen age of father in each year
	gen father_b_year=year_treat - age_father_inp
	gen age_father=year_calendar - father_b_year

	* dummify time_event, with -2 as omitted variable
	** all but i_time_even_4 (-2 time_event)
	xi i.time_event,prefix("i_") noomit
	global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
	i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

	* g interactions 
	local time_to_shock = -5 
	forvalues i= 1(1)9{
		g even`i'_treat = i_time_even_`i'*treat
		label var even`i'_treat "`time_to_shock'"
		local ++time_to_shock 
	}

	** all but i_time_even_4 (-2 time_event)
	global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
	even6_treat even7_treat even8_treat even9_treat

	forvalues i= 1(1)3{
		local x = `i' + 6 
		label var i_time_even_`x' "`i' years after hospitalization" 
	}
	forvalues i= 1(1)5 {
		local x =  6 - `i'
		label var i_time_even_`i' "`x' years before hospitalization"
	}

	label var i_time_even_6 "Year of hospitalization" 

	* Table A16
	** Set controls
	global controls i.treat i.age_mother i.age_father ///
	i.year_calendar i.child_b_year i.educ0 i.father_educ0 male

	** Implement conditions
	keep if $sample_did
	
	** Earnings (Euro)
	reg income $event_dummies $event_treat_dummies $controls, cluster(shnro_mother)
	estimates store incomemom_`time'
	estadd local controls "YES"
	sum income if time_event == -2
	estadd scalar ymean = r(mean)

} 

* Mothers
esttab incomemom_week incomemom_month ///
using "$output\table A16_fi.tex", label ///
addnotes("This table shows the impact of children's hospital admission or fatal shock on maternal earnings in Euros for the sample of mothers who did not experience a hospitalization or mortality themselves at the same time as the child (t = +- 7 days) or (t = +- 30 days).") ///
mtitles("Earnings Mom Hospitalization Week (\euro)" "Earnings Mom Hospitalization Month (\euro)") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean $Y_{t-2}$") ///
replace star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) 

}

**********************************************************
* Table A17: Mortality: Mutual Shocks
**********************************************************
{
estimates clear
foreach time in week month {
	
	use "$processed_data\date_mortality.dta", clear 
	merge 1:m shnro_mother using ///
	"$processed_data\mothers_income_diagnosis4_mortality_acc_`time'", keep(3) nogen 
	merge 1:1 shnro_mother treat using ///
	"$processed_data\fathers_income_diagnosis4_mortality_acc_`time'", keep(3) nogen 
	
	* Put in long format
	keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp income_* ///
	father_income_* educ0 child_b_year father_educ0 male treat ageinptreat year_treat

	egen new_shnromother = group(shnro_mother treat)
	reshape long income_ father_income_ ,i(new_shnromother) j(year_event) string
	rename income_ income
	rename father_income_ father_income

	* gen time event 
	gen time_event=.
	forvalues x=0(1)3{
		replace time_event=`x' if year_event=="year`x'"
	}
	forvalues x=1(1)5{
		replace time_event=-`x' if year_event=="yearminus`x'"
	}

	* gen year of income (calendar year)
	gen year_calendar=year_treat+time_event

	* gen age of mother in each year
	gen mother_b_year=year_treat - age_mother_inp
	gen age_mother=year_calendar-mother_b_year

	* gen age of father in each year
	gen father_b_year=year_treat - age_father_inp
	gen age_father=year_calendar - father_b_year

	* dummify time_event, with -2 as omitted variable
	** all but i_time_even_4 (-2 time_event)
	xi i.time_event,prefix("i_") noomit
	global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
	i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

	* g interactions 
	local time_to_shock = -5 
	forvalues i= 1(1)9{
		g even`i'_treat = i_time_even_`i'*treat
		label var even`i'_treat "`time_to_shock'"
		local ++time_to_shock 
	}

	** all but i_time_even_4 (-2 time_event)
	global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
	even6_treat even7_treat even8_treat even9_treat

	forvalues i= 1(1)3{
		local x = `i' + 6 
		label var i_time_even_`x' "`i' years after hospitalization" 
	}
	forvalues i= 1(1)5 {
		local x =  6 - `i'
		label var i_time_even_`i' "`x' years before hospitalization"
	}

	label var i_time_even_6 "Year of hospitalization"

	* Table A10
	** Set controls
	global controls_mother i.treat i.age_mother ///
	i.year_calendar i.child_b_year male

	** Restrict sample 
	keep if $sample_did_mortality
	
	** Earnings (Euro)
	reg income $event_dummies $event_treat_dummies $controls_mother, cluster(shnro_mother)
	estimates store incomemom_`time'
	estadd local controls "YES"
	sum income if time_event == -2
	estadd scalar ymean = r(mean)
	
} 

* Output
esttab incomemom_week incomemom_month ///
using "$output\table A17_fi.tex", label ///
addnotes("This table shows the impact of children's mortality on maternal and paternal earnings in Euro. Sample is restricted to children whose parents did not experience a mortality shock themselves at the same time as the child (t = +- 30 days).") ///
mtitles("Earnings Mom (\euro)" "Earnings Dad (\euro)") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean $Y_{t-2}$") ///
replace star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) 

esttab incomemom_week incomemom_month ///
using "$output\table A17_fi", label ///
addnotes("This table shows the impact of children's mortality on maternal and paternal earnings in Euro. Sample is restricted to children whose parents did not experience a mortality shock themselves at the same time as the child (t = +- 30 days).") ///
mtitles("Earnings Mom (\euro)" "Earnings Dad (\euro)") ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean $Y_{t-2}$") ///
replace star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) smcl
}

**********************************************************
* Table A18 & Table 3 column 1: Hospitalizations: Parents' Number of Mental Health Visits
**********************************************************
{

use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using "$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using "$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
mentalhealth* educ0 child_b_year income_* father_income_* ///
father_educ0 male treat ageinptreat year_treat
rename mentalhealthdad* dadmentalhealth*

egen new_shnromother = group (shnro_mother treat)
reshape long mentalhealth dadmentalhealth income_ father_income_ ///
, i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income

* gen numeric variable for time w.r.t to the hospitalization
gen time_event=.
forvalues x=0(1)3{
	replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
	g even`i'_treat = i_time_even_`i'*treat
	label var even`i'_treat "`time_to_shock'"
	local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
	local x = `i' + 6 
	label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
	local x =  6 - `i'
	label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* generate post dummy
gen post = time_event >= 0
tab post 
* generate post*treat interaction dummy
gen posttreat = post*treat 

* Table A18
** Set controls
global controls i.treat i.age_mother i.age_father ///
i.year_calendar i.child_b_year i.educ0 i.father_educ0 male

** Restrict sample 
keep if $sample_mh

estimates clear 
reg mentalhealth $event_dummies $event_treat_dummies $controls, cluster(shnro_mother)
estimates store mhmom
estadd local controls "YES"
sum mentalhealth if time_event == -2 
estadd scalar ymean = r(mean)

reg dadmentalhealth $event_dummies $event_treat_dummies $controls, cluster(shnro_father)
estimates store mhdad
estadd local controls "YES"
sum dadmentalhealth if time_event == -2
estadd scalar ymean = r(mean)

esttab mhmom mhdad ///
using "$output\table A18_fi.tex", label replace ///
addnotes("This table shows the impact of children's hospital admission on the number and probability of a mother's or father's mental health encounter. Each effect is estimated using matched DiD hospitalizations") ///
mtitles("Number of Mental Health Visits Mom" "Number of Mental Health Visits Dad" "Prob. Mental Health Visit Mom" "Prob. Mental Health Visit Dad" ) ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat ) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)




** Table 3 column 1
reg  mentalhealth post treat posttreat $controls, cluster(shnro_mother)
	estimates store mental_mom
	estadd local controls "YES"
	sum  mentalhealth if time_event == -2
	estadd scalar ymean = r(mean)
	

** Output
esttab mental_mom ///
using "$output\table 3_fi.tex", label replace ///
addnotes("This table shows the impact of children's hospital admission on number of mother's mental health encounter. The table shows the estimated coefficients for the interaction between the post and the treat dummy. We use administrative data from Finland. All specifications include controls for calendar year, child's year of birth, child's gender, and each parent's age and educational level. Standard erros are clustered at the parent level.'") ///
mtitles("Mental") ///
keep(posttreat) ///
scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)
}

**********************************************************
* Table A19: Mortality: Parents' Number of Mental Health Visits
**********************************************************
{
use "$processed_data\date_mortality.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4_mortality_acc", keep(3) nogen  
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4_mortality_acc", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
mentalhealth* educ0 child_b_year income_* father_income_* ///
father_educ0 male treat ageinptreat year_treat
rename mentalhealthdad* dadmentalhealth*

egen new_shnromother = group (shnro_mother treat)
reshape long mentalhealth dadmentalhealth income_ father_income_ ///
, i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income

* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
	replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
	replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
	g even`i'_treat = i_time_even_`i'*treat
	label var even`i'_treat "`time_to_shock'"
	local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
	local x = `i' + 6 
	label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
	local x =  6 - `i'
	label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table A11
** Set controls
global controls_mother i.treat i.age_mother ///
i.year_calendar i.child_b_year male
global controls_father i.treat i.age_father ///
i.year_calendar i.child_b_year male

** Restrict sample 
keep if $sample_mh_mortality

estimates clear 
reg mentalhealth $event_dummies $event_treat_dummies $controls_mother ///
if !missing(income), cluster(shnro_mother)
estimates store mhmom
estadd local controls "YES"
sum mentalhealth if time_event == -2
estadd scalar ymean = r(mean)

reg dadmentalhealth $event_dummies $event_treat_dummies $controls_father ///
if !missing(father_income), cluster(shnro_father)
estimates store mhdad
estadd local controls "YES"
sum dadmentalhealth if time_event == -2 
estadd scalar ymean = r(mean)

esttab mhmom mhdad ///
using "$output\table A19_fi.tex", label replace ///
addnotes("This table shows the impact of children's hospital admission on the number and probability of a mother's or father's mental health encounter. Each effect is estimated using matched DiD hospitalizations") ///
mtitles("Number of Mental Health Visits Mom" "Number of Mental Health Visits Dad" "Prob. Mental Health Visit Mom" "Prob. Mental Health Visit Dad" ) ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat ) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)
** Number of visits
esttab mhmom mhdad ///
using "$output\table A19_fi", label replace ///
addnotes("This table shows the impact of children's hospital admission on the number and probability of a mother's or father's mental health encounter. Each effect is estimated using matched DiD hospitalizations") ///
mtitles("Number of Mental Health Visits Mom" "Number of Mental Health Visits Dad" "Prob. Mental Health Visit Mom" "Prob. Mental Health Visit Dad" ) ///
keep(even1_treat even2_treat even3_treat even5_treat even6_treat ///
even7_treat even8_treat even9_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) smcl
}

**********************************************************
* Table A20: Heterogeneous impact by HH specialization 
**********************************************************
{
use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Put in long format
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 income* father_income* 

egen new_shnromother = group(shnro_mother treat)
reshape  long income_ father_income_ , ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income

 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

* Table 3
** Set controls
global controls i.treat i.age_mother i.age_father i.year_calendar ///
i.child_b_year i.educ0 i.father_educ0 male

** Implement conditions
keep if $sample_did
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat

** generate dummies for main or second eaerner 
gen mom_1earner1 = 1 if income > father_income & time_event ==-2
bysort shnro_mother: egen mom_1earner = max(mom_1earner1)
gen mom_2earner1 = 1 if income <= father_income & time_event ==-2
bysort shnro_mother: egen mom_2earner = max(mom_2earner1)
drop mom_1earner1 mom_2earner1


** generate dummies but considering the average from -2 to -5
bysort shnro_mother: egen mompreincome1 = mean(income) if time_event >= -5 & time_event <= -2
bysort shnro_mother: egen mompreincome= max(mompreincome1)
bysort shnro_father: egen dadpreincome1 = mean(father_income) if time_event >= -5 & time_event <= -2
bysort shnro_father: egen dadpreincome= max(dadpreincome1)

gen mom_1earner1 = 1 if mompreincome > dadpreincome & time_event ==-2
bysort shnro_mother: egen mom_1earner2 = max(mom_1earner1)
gen mom_2earner1 = 1 if mompreincome <= dadpreincome & time_event ==-2
bysort shnro_mother: egen mom_2earner2 = max(mom_2earner1)
drop mom_1earner1 mom_2earner1

** generate share of income 

* replace 0s to be able to take shares 
generate father_income2 = father_income
replace father_income2 = 1 if father_income == 0 
generate income2= income
replace income2 = 1 if income == 0 

gen share_income = income/(father_income + income) 
gen share0_25 = 1 if share_income < 0.25
gen share25_50 =1 if share_income >= 0.25 & share_income < 0.5
gen share50_75 = 1 if share_income >= 0.5 & share_income < 0.75
gen share75_100 = 1 if share_income >= 0.75 

gen share0_40 = 1 if share_income < 0.40
gen share40_60 =1 if share_income >= 0.4 & share_income <= 0.6
gen share60_100 = 1 if share_income > 0.6  


 
/* definition from -2 to -5*/
foreach var in mom_1earner2 mom_2earner2 { 

** Income 
reg income post treat post_treat $controls if `var' == 1, cluster(shnro_mother) coeflegend
estimates store income`var'
estadd local controls "YES"
sum income if time_event == -2 & `var' ==1
estadd scalar ymean = r(mean)

}

* Output Mothers 
esttab incomemom_1earner2 incomemom_2earner2 ///
using "$output\table 20het-2-5_fi.tex", label replace ///
addnotes("This table shows the impact of a child's hospitalization on maternal earnings for primary earner mothers (in column (1)) and secondry earner mothers (in column (2)) (defined from average earnings from -2 to -5), for both Finland and Norway, respectively. The table shows the coefficient for the interaction between a post dummy (after hospitalization) and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Primary" "Secondary" ) ///
keep(post_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3)


}

**********************************************************
* Table A22: Heterogeneous impact by marital status 
**********************************************************
{
use "$processed_data\date_diagnosis.dta", clear 
merge 1:m shnro_mother using ///
"$processed_data\mothers_income_diagnosis4", keep(3) nogen 
merge 1:1 shnro_mother treat using ///
"$processed_data\fathers_income_diagnosis4", keep(3) nogen 

* Put in long format
drop married /* this variable comes from birth registry, we want to use marital status in -2*/
keep yearinp shnro_mother shnro_father age_mother_inp age_father_inp ///
child_b_year male treat ageinptreat year_treat educ0 father_educ0 income* father_income* divorced* married* unmarried* widowed* mother_kids*

egen new_shnromother = group(shnro_mother treat)
reshape  long income_ father_income_ divorced_ married_ unmarried_ widowed_ mother_kids_, ///
i(new_shnromother) j(year_event) string
rename income_ income
rename father_income_ father_income
rename divorced_ divorced
rename married_ married
rename unmarried_ unmarried
rename widowed_ widowed
rename mother_kids_ mother_kids
 
* gen numeric variable for time w.r.t hospitalization 
gen time_event=.
forvalues x=0(1)3{
replace time_event=`x' if year_event=="year`x'"
}
forvalues x=1(1)5{
replace time_event=-`x' if year_event=="yearminus`x'"
}

* gen year of income (calendar year)
gen year_calendar=year_treat + time_event

* gen age of mother in each year
gen mother_b_year=year_treat - age_mother_inp
gen age_mother=year_calendar - mother_b_year

* gen age of father in each year
gen father_b_year=year_treat - age_father_inp
gen age_father=year_calendar - father_b_year

* dummify time_event, with -2 as omitted variable
** all but i_time_even_4 (-2 time_event)
xi i.time_event,prefix("i_") noomit
global event_dummies i_time_even_1 i_time_even_2 i_time_even_3 i_time_even_5 ///
i_time_even_6 i_time_even_7 i_time_even_8 i_time_even_9

* g interactions 
local time_to_shock = -5 
forvalues i= 1(1)9{
g even`i'_treat = i_time_even_`i'*treat
label var even`i'_treat "`time_to_shock'"
local ++time_to_shock 
}

** all but i_time_even_4 (-2 time_event)
global event_treat_dummies even1_treat even2_treat even3_treat even5_treat ///
even6_treat even7_treat even8_treat even9_treat

forvalues i= 1(1)3{
local x = `i' + 6 
label var i_time_even_`x' "`i' years after hospitalization" 
}
forvalues i= 1(1)5 {
local x =  6 - `i'
label var i_time_even_`i' "`x' years before hospitalization"
}

label var i_time_even_6 "Year of hospitalization" 

** Set controls
global controls i.treat i.age_mother i.age_father i.year_calendar ///
i.child_b_year i.educ0 i.father_educ0 male

** Implement conditions
keep if $sample_did
g post =  1 if time_event >= 0 
replace post = 0 if post ==.
g post_treat = post*treat

** generate dummies for heterogeneity analysis
foreach var in married unmarried divorced widowed  { 
gen `var'_mom1 = 1 if `var' == 1 & time_event == -2
replace `var'_mom1 = 0 if `var'_mom1 == .
bysort shnro_mother: egen `var'_mom= max(`var'_mom1)
}



foreach var in married unmarried divorced widowed  { 

** Income 
reg income post treat post_treat $controls if `var'_mom == 1, cluster(shnro_mother) coeflegend
estimates store income`var'
estadd local controls "YES"
sum income if time_event == -2 & `var' ==1
estadd scalar ymean = r(mean)

}


** single mothers vs rest of mothers
gen mother_kids_mom1 = 1 if mother_kids == 1 & time_event == -2
replace mother_kids_mom1 = 0 if mother_kids_mom1 == .
bysort shnro_mother: egen mother_kids_mom= max(mother_kids_mom1)

reg income post treat post_treat $controls if mother_kids == 1, cluster(shnro_mother) coeflegend
estimates store incomesingle
estadd local controls "YES"
sum income if time_event == -2 & mother_kids ==1
estadd scalar ymean = r(mean)

* Output Mothers 
esttab incomemarried  incomedivorced incomeunmarried incomesingle ///
using "$output\table A22het_fi.tex", label replace ///
addnotes("This table shows the impact of a child's hospitalization on maternal earnings for married women (in column (1)) unmarried women (in column (2)), divorced women (in column (3)), and single women (in column (4)), for both Finland and Norway, respectively. The table shows the coefficient for the interaction between a post dummy (after hospitalization) and the treat dummy in equation \ref{didequation}. All specifications include controls for calendar year, child's year of birth, child's gender, age of the parent, and parent's education level. Clustered standard errors at the parent level.") ///
mtitles("Married" "Divorced" "Unmarried" ///
"Single") ///
keep(post_treat) scalars ("controls Controls" "ymean Mean \$Y_{t-2}$") ///
star(* 0.10 ** 0.05 *** 0.01) b(3) se(3) 





}

